Search code examples
cfunctionrecursiondefinitiondigits

C - turn 9 to 0


It's my first question here and I'm a beginner, the code is written in C (ANSI C).

The code should return the digits as (n+1) for each digit in a recursive function.(123 -> 234; 801->912; 239->340)

The problem is when the digit 9 appears and the code adds it 1 the result is 10 and it's required to become 0. Is there a way to handle it without checking specially for the digit 9?

Thanks!

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

Solution

  • Recursively, the simplest approach would be:

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

    What this function says is:

    • If n is less than 10, the result is 1 larger than its current value, modulo 10.
      Thus, 9 would become (10 mod 10), which would be 0.
    • Otherwise, recursively apply the algorithm against the last digit and the rest of the digits.
      The trick here is that the rest of the digits is obtained by dividing the original number by 10, and multiplying the received result by 10.