春节每日一题~(自除数)

728. 自除数 - 力扣(LeetCode)

春节每日一题~(自除数)_第1张图片

#include   
  
int* selfDividingNumbers(int left, int right, int* returnSize) {  
    int* result = (int*)malloc((right - left + 1) * sizeof(int));  
    if (result == NULL) {  
        // 内存分配失败  
        *returnSize = 0;  
        return NULL;  
    }  
  
    int count = 0; // 用于跟踪结果数组中的自除数数量  
  
    for (int i = left; i <= right; i++) {  
        int temp = i;  
        int divisible = 1;  
  
        // 检查当前数字是否为自除数  
        while (temp > 0) {  
            int digit = temp % 10;  
            if (digit == 0 || i % digit != 0) {  
                divisible = 0;  
                break;  
            }  
            temp /= 10;  
        }  
  
        // 如果是自除数,则添加到结果数组中  
        if (divisible) {  
            result[count++] = i;  
        }  
    }  
  
    // 设置返回数组的大小  
    *returnSize = count;  
  
    return result;  
}

 238. 除自身以外数组的乘积 - 力扣(LeetCode)

 春节每日一题~(自除数)_第2张图片

 

#include   
  
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {  
    if (nums == NULL || numsSize == 0) {  
        *returnSize = 0;  
        return NULL;  
    }  
  
    *returnSize = numsSize;  
    int* answer = (int*)malloc(numsSize * sizeof(int));  
    int* leftProducts = (int*)malloc(numsSize * sizeof(int));  
    int* rightProducts = (int*)malloc(numsSize * sizeof(int));  
  
    // 初始化左侧乘积数组,第一个元素左侧没有元素,乘积为1  
    leftProducts[0] = 1;  
    for (int i = 1; i < numsSize; ++i) {  
        leftProducts[i] = leftProducts[i - 1] * nums[i - 1];  
    }  
  
    // 初始化右侧乘积数组,最后一个元素右侧没有元素,乘积为1  
    rightProducts[numsSize - 1] = 1;  
    for (int i = numsSize - 2; i >= 0; --i) {  
        rightProducts[i] = rightProducts[i + 1] * nums[i + 1];  
    }  
  
    // 计算答案数组  
    for (int i = 0; i < numsSize; ++i) {  
        answer[i] = leftProducts[i] * rightProducts[i];  
    }  
  
    // 释放辅助数组  
    free(leftProducts);  
    free(rightProducts);  
  
    return answer;  
}

你可能感兴趣的:(算法,数据结构)