C 递归 - 将数字的每个数字加 1,除了数字 9 为 0

标签 c function recursion numbers digits

我已经成功创建了一个函数,该函数将每个数字的数字(0-8)加 1。

示例: 输入:3 输出:4

输入:345 输出:456

但是我在寻找需要返回 0 的数字 9 的解决方案时遇到问题。

示例: 输入:9 输出:0

输入:945 输出:56

输入:99 输出:0

输入:19 输出:20

注意: 不专门检查数字是否为9

我的代码:

int new_num(int num){
    int dig = num%10;
    num = num/10;

    if( num==0 ){
        return dig+1;
    }
    int res = new_num(num);
    dig +=1;
    res *=10;
    res +=dig;
    return res;   
}

谢谢。

最佳答案

给你。

#include <stdio.h>

int new_num( int n )
{
    const int Base = 10;

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

int main(void) 
{
    printf( "%d -> %d\n", 99, new_num( 99 ) );
    printf( "%d -> %d\n", 945, new_num( 945 ) );
    printf( "%d -> %d\n", 19, new_num( 19 ) );
    printf( "%d -> %d\n", 123456789, new_num( 123456789 ) );

    return 0;
}

程序输出为

99 -> 0
945 -> 56
19 -> 20
123456789 -> 234567890

关于C 递归 - 将数字的每个数字加 1,除了数字 9 为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59406816/

相关文章:

java - 使用递归打印长度 X 的所有组合

algorithm - 是否有任何理由选择迭代算法而不是递归算法

recursion - 创建递归可区分联合值

c - 不正确的结果 - Intel HD 4000 上的 OpenCL

c - Notepad++ 和 stdint.h 类型

c - C中的手动名称修改

python - 在 Python 中访问 R 用户定义的函数

python - 如何在由python中的另一个函数创建之前读取文本文件

c - 如何使用 C 检索当前 Windows 用户登录?

Javascript - 让函数告诉调用者函数何时完成