简体   繁体   中英

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

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

It seems you mean the following

#include <stdio.h>

unsigned int increase_digits( unsigned int n )
{
    const unsigned int Base = 10;

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

int main(void) 
{
    unsigned int n = 0;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 9;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 13;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 801;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 239;

    printf( "%u: %u\n", n, increase_digits( n ) );

    return 0;
}

The program output is

0: 1
9: 0
13: 24
801: 912
239: 340

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.

A version that prints 00 for an input of 99

int swap(int num) {
     return num/10 ?
        swap(num/10)*10 + ((num % 10 + 1)%10) :
        (num % 10 + 1) % 10;
}

The swap caller function determines the length of the integer parameter, then displays any necessary leading zeroes.

void caller(int num) {
     char s[20];             // Assume an int as at most 19 chars...
     sprintf (s, "%d", num); // Could also use log or a loop...

     printf("result: %0*d\n", (int)strlen(s), swap(num));    
}

Use it as

caller(mynumber);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM