Do the following function using recursion . // shift_digits(n) returns the number consisting of the decimal digits
Question:
Do the following function using recursion.
// shift_digits(n) returns the number consisting of the decimal digits of n // shifted forward by 1, so 123 becomes 234 (the digit 9 does not get changed) // requires: 0 <= n < 1,000,000,000 int shift_digits(int n);
Here are the sample inputs:
inputCopy123 outputCopy234 inputCopy9999outputCopy9999 inputCopy0outputCopy1 inputCopy11911outputCopy22922
SO as we can see the 9's will remain uunchanged. If i put in 0 it should become one and If i put in a regular number then increment each digit by 1 and print it. If the normal number has a 9 in it increment everything around it except the 9. This is the code I have so far but it fails when i put in 0 as it does not give me one and it fails when i put in a number with a 9 as it also increments the 9. Please help.
My code. (THis is in C
#include
int shift_digits(int n) { // Base case: if n is 0, return 0 if (n == 0) { return 0; }
// Process the last digit int last_digit = n % 10; if (last_digit != 9) { last_digit += 1; }
// Recursively call shift_digits for the remaining digits return shift_digits(n / 10) * 10 + last_digit; }
int main(void) { int n = 0; scanf("%d", &n); printf("%d ", shift_digits(n)); return 0; }
Use the following main function exactly:
int main(void) { int n = 0; scanf("%d", &n); printf("%d\n", shift_digits(n)); }
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill