recursive function digits of a positive decimal integer in reverse order c++

天涯浪子 提交于 2019-12-04 04:54:06

问题


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 correctly. I know im supposed to use % or 10 when displaying the number and / of 10 when in the recursive call as well as the base case is supposed to be < 10. Here is my code.

#include <iostream>
using namespace std;

int reverse(int,int);

int main()
{
    int number;
    int n;

    cout << " Enter number to reverse." << endl;
    cin >> number;
    cout << reverse(number % 10,0);

    return 0;
}//end main

int reverse(int number,int n)
{

    if(n < 10)
    {
        return n;
    }
    else
    {
        return reverse(number/10,n);
    }
}// end reverse

回答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 
    }
}



回答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);
}



回答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);
  }
}



回答4:


You could also do:

int reverse(int number,int n) {
if(number > n) {
    cout << number << endl;
    reverse(number-1,n);
}

But you should get rid of first number printing twice.




回答5:


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.



来源:https://stackoverflow.com/questions/12270843/recursive-function-digits-of-a-positive-decimal-integer-in-reverse-order-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!