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;
}
}
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:
n
is less than 10, the result is 1 larger than its current value, modulo 10.