c - 如何在C中计算无符号长数中的奇数位

标签 c

我的教授对此的规则是:

编写一个带有签名的递归函数:

int check_odd(unsigned long n);

该函数获取一个自然正数n。该函数需要检查n中出现的不同奇数位的个数是否小于3。如果是:返回1,否则返回0。 您不能使用任何其他函数,也不能使用静态/全局变量。

示例:

check_odd(2169876)==0 
check_odd(956908529)==1

这是我到目前为止所做的代码,它在一定程度上有效:

 int check_odd(unsigned long n) {      
    if (n / 10 == 0) {
        return n % 2 != 0 ? 1 : 0;
    }
    else {
        return (n % 10 % 2 != 0? 1:0)+check_odd(n/10);
    }
}

这个递归函数返回数字中有多少个奇数位。现在我不知道如何继续检查数字是否相同或不同,如果有3个或更多不同的奇数位,我需要返回0;其他1.

最佳答案

@Daniel Beck Bachar:你把数字 3 × 3 处理的想法很友善。它激励我寻找解决方案。 另请注意 (n&1) 与 n%2 相同。

#include <stdio.h>

int check_odd(unsigned long n)
{
    int d1, d2, d3, n2;

    if (n < 100)
        return 1;

    d1 = n%10; // digit for units
    d2 = (n/10)%10; // digit for tens
    d3 = (n/100)%10; // digit for hundreds

    // We try to remove some of the three digits
    // A digit can be removed if it is even
    // Or if it is the same as another of the 2 other digit
    n2 = n / 1000;
    if ((d3&1) == 1)
        n2 = n2*10 + d3;
    if ((d2&1) == 1 && d2 != d3)
        n2 = n2*10 + d2;
    if ((d1&1) == 1 && d1 != d2 && d1 != d3)
        n2 = n2*10 + d1;
    if (n == n2) // If all 3 digits are kept, that means they are all odd and differents
        return 0;

    return check_odd(n2); // Since n2 < n, one day or the other the recursion will end.
}

int main(int argc, char **argv)
{
    unsigned int n;

    n = atoi(argv[1]);
    printf("check_odd(%d) = %d\n", n, check_odd(n));
    return 0;
}

编辑:由于运算符优先级,我在 (n&1) 两边加上括号,因为 == 首先计算。感谢 chqrlie。

关于c - 如何在C中计算无符号长数中的奇数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474249/

相关文章:

不明白为什么我在 C 中打开文件时总是出错

c - "C"用分隔符按空格分割字符串,但在某些单词之间转义空格(姓氏、名字)

c - 将已删除的文件重新附加到目录

c - 两种格式的 printfs 的反汇编代码

c - C 中的时间戳

c++ - 同一文件流中的 fread 和 fgetc 不起作用

c - #define C用法,取多个值

c - Do while 不按顺序获取输入定义它仅适用于 1 scanf

macos - 将指针转换到 int 和警告?

c - linux中strtok定义的位置