繁体   English   中英

C - 将 9 转为 0

[英]C - turn 9 to 0

这是我在这里的第一个问题,我是初学者,代码是用 C (ANSI C) 编写的。

代码应该为递归函数中的每个数字返回数字为 (n+1)。(123 -> 234; 801->912; 239->340)

问题是当数字 9 出现并且代码将其加 1 时,结果是 10 并且它需要变为 0。有没有办法处理它而无需专门检查数字 9?

谢谢!

int swap(int num)
{
    int a,b;
    if (num/10==0)
        return num+1;
    else
    {
        a = num % 10;
        a++;
        b = swap(num / 10);
        return (b * 10) + a;
    }
}

为了在不检查的情况下获得下一个数字,您只需使用 MOD 运算符 % 环绕。 所以a = (num % 10 + 1) % 10或者更简单的a = (num + 1) % 10正如迈克尔所指出的

看来你的意思是以下

#include <stdio.h>

unsigned int increase_digits( unsigned int n )
{
    const unsigned int Base = 10;

    return ( n + 1 ) % Base + ( n / Base == 0  ? 0 : Base * increase_digits( n / Base ) ); 
}

int main(void) 
{
    unsigned int n = 0;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 9;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 13;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 801;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 239;

    printf( "%u: %u\n", n, increase_digits( n ) );

    return 0;
}

程序输出是

0: 1
9: 0
13: 24
801: 912
239: 340

递归地,最简单的方法是:

unsigned swap (unsigned n) {
    if (n < 10) return ++n % 10;
    return 10 * swap(n/10) + swap(n%10);
}

这个函数说的是:

  • 如果n小于 10,则结果比其当前值大 1,取模 10。
    因此,9 将变为 (10 mod 10),即 0。
  • 否则,对最后一位数字和其余数字递归应用该算法。
    这里的技巧是,其余的数字是通过将原始数字除以 10,并将接收到的结果乘以 10 得到的。

输入99打印00的版本

int swap(int num) {
     return num/10 ?
        swap(num/10)*10 + ((num % 10 + 1)%10) :
        (num % 10 + 1) % 10;
}

交换调用函数确定整数参数的长度,然后显示任何必要的前导零。

void caller(int num) {
     char s[20];             // Assume an int as at most 19 chars...
     sprintf (s, "%d", num); // Could also use log or a loop...

     printf("result: %0*d\n", (int)strlen(s), swap(num));    
}

将其用作

caller(mynumber);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM