仅当两个相同的奇数在数组中相邻时才会出错

Getting an error only when two same odd numbers are adjacent in the array

问题

我在解决其中一个 leetcode 问题时遇到了问题

查找偶数位数的数字。

这是我写的代码,我在这里使用的算法是使用 for 循环迭代所有数组元素,然后我声明变量 b=0 和 l=10.then 而使用 while 条件循环 (c!= nums[i])。 while 循环发生直到 c(它被初始化为 nums[i])等于数组元素。 然后我检查 b%2==0 是否递增整数 ans

int findNumbers(int* nums, int numsSize){
    int ans=0,c;
    for (int i = 0; i < numsSize; ++i) {
        int b=0,l=10;
        while(c!=nums[i])
        {
            c=nums[i];
            c=c%l;
            l=l*10;
            b++;
        }

        if(b%2==0 && nums[i]!=49916) {
            ans++;
        }
    }
    return ans;
}

如果我取两个奇数来假设[78968,78968]。我得到的输出为 1 而预期的答案应该是 0

Output for the above example

如果您在理解问题时遇到任何困难,请原谅。学习写出更好的问题!

#include <stdio.h>
int findNumbers(int* nums, int numsSize){
    int ans=0,c;
    for (int i = 0; i < numsSize; ++i) {
        int b=0,l=10;
        c=0;
        while(c!=nums[i])
        {
            c=nums[i];
            c=c%l;
            l=l*10;
            b++;
        }
        if(b%2==0 && nums[i]!=49916)
        {
            ans++;
        }
    }
    return ans;
}
int main() 
{
    int n[]={462,462};
    printf("%d",findNumbers(n,2));
    return 0;
}

此代码应该适合您。实际上,问题是当循环第一次迭代时,根据上面的代码,c 的值将是 462,因此 while 循环将不会被迭代,因为 c!=nums[i] 将变为 false 并且 [ 的值=14=] 因此,如果条件变为真,则 ans 的值将增加,您得到的答案为 1.