Search code examples
cfunctionrecursionnumbersdigits

C recursion - increase each digit of a number by 1 except digit number 9 which will be 0


i already managed to create a function which returns every number's digit(0-8) by 1.

example : input : 3 output: 4

input : 345 output: 456

But i have a problem finding a solution for digit number 9 which need to return 0 .

example: input : 9 output: 0

input : 945 output: 56

input : 99 output: 0

input : 19 output: 20

NOTE: Do not specifically check if the digit is 9

my code:

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;   
}

thanks.


Solution

  • Here you are.

    #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;
    }
    

    The program output is

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