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

前端 未结 5 504
清歌不尽
清歌不尽 2021-01-21 18:22

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

相关标签:
5条回答
  • 2021-01-21 18:35

    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.

    0 讨论(0)
  • 2021-01-21 18:36

    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 
        }
    }
    
    0 讨论(0)
  • 2021-01-21 18:39
    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.

    0 讨论(0)
  • 2021-01-21 18:43

    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-21 18:45

    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);
    }
    
    0 讨论(0)
提交回复
热议问题