简体   繁体   中英

C language, increase each number of sequence by 1. how to remove 0 in the begining

You receive a number. Function should create a new number by changing each number (d=1,2,3,...) of the number to d+1. If 9 is in the middle of the number will be turned into 0. You should not check if the specific number is 9 (!) . The function should return a new number.

The problem in my code is that when I get a number that starts with 9, in the beginning it shows 0 (but it shouldn't as shown in examples below).

//if input 879021 - output 980132
//if input 930 - output 41
//if input 9999 - output 0
//working with visual studio 2017

void num_incr(int number);

void main(){
   int number = 0;
   printf("Enter a whole number: ");
   scanf_s("%d", &number);
   num_incr(number);
}

void num_incr(int number) {
   if (number <= 0) {
      return;
   }
   num_incr(number / 10);
   printf("%d", (number % 10 + 1) % 10);
}

To remove 0 in beginning, first make the return function as integer and print at last.

also In current code, the recursion is not finished because positive integer will be still positive when it is divided by 0.

//if input 879021 - output 980132
//if input 930 - output 41
//if input 9999 - output 0
//working with visual studio 2017

int num_incr(int number);

void main(){
   int number = 0;
   printf("Enter a whole number: ");
   scanf_s("%d", &number);
   printf("%d\n", num_incr(number));
}

int num_incr(int number) {
   if (number <= 0) {
      return 0;
   }
   int up_part = num_incr(number / 10);
   return up_part * 10 + ((number % 10 + 1) % 10);
}

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