I have an assignment to write a recursive function that writes the digits of a positive integer in reverse order. My problem is that the function doesn\'t display the reverse co
int rev(int n) {
if(n<10&&n>-10) return n;
int length=0;
for (int i=n; i; i/=10) length++;
return n%10*(int)pow(10, length-1) + rev(n/10);
}
Here's my solution. It takes only one parameter and return an int. Also don't forget to include cmath.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l;
}
int rev(int n) {
return n<10&&n>-10 ? n : n%10*(int)pow(10, intLength(n)-1) + rev(n/10);
}
Or this way it's a bit more elegant.