Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 658
AG19 Avatar asked Dec 29 '25 22:12

AG19


2 Answers

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.
like image 59
jxh Avatar answered Dec 31 '25 12:12

jxh


In order to get the next digit without checking you just have to wrap around using MOD operator %. So a = (num % 10 + 1) % 10 or even simpler a = (num + 1) % 10 as pointed out by Michael

like image 40
The Javatar Avatar answered Dec 31 '25 12:12

The Javatar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!