recursive function digits of a positive decimal integer in reverse order c++
Solution 1:
I think this is what your function should be:
void reverse(int number){
if(number == 0) //base/basic case i.e if number is zero the problem is already solved, nothing to do, so simply return
return;
else{
cout << number % 10; // print that last digit, e.g 103%10 == 3
reverse(number/10); //solve the same problem but with smaller number, i.e make the problem smaller by dividing it by 10, initially we had 103, now 10
}
}
Solution 2:
You could use following code (if you do not mind striping leading zeros, or you could accumulate chars in string or ostringstream)
unsigned reverse(unsigned n, unsigned acc)
{
if (n == 0)
{
return acc;
}
else
{
return reverse(n / 10, (acc * 10) + (n % 10));
}
}
unsigned reverse(unsigned n)
{
return reverse(n, 0);
}
Solution 3:
This solution will omit trailing zeroes, because it is literally reversing the content of the integer:
int reverse(int number, int n = 0)
{
if (number == 0)
{
return n;
}
else
{
int nextdigit = number%10;
int nextprefix = n*10+nextdigit;
return reverse(number/10 ,nextprefix);
}
}