Recursion to the rescue! | LeetCode
Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
Think of recursion as the allocation of a stack… Push the last digit onto the stack, then continue with the 2nd last, …, up until the first digit. Then when the function pops off the stack, you get the digit in the correct order. Voila!
Print a string in reverse order.
Read full article from Recursion to the rescue! | LeetCode
Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
Think of recursion as the allocation of a stack… Push the last digit onto the stack, then continue with the 2nd last, …, up until the first digit. Then when the function pops off the stack, you get the digit in the correct order. Voila!
2
3
4
5
6
7
8
|
void putlong(unsigned long n) {
if (n < 10) {
putchar(n + '0');
return;
}
putlong(n / 10);
putchar(n % 10 + '0');
}
|
void printReverse(const char *str) {
if (!*str)
return;
printReverse(str + 1);
putchar(*str);
}
Reversing linked-list can be done recursively too.Read full article from Recursion to the rescue! | LeetCode