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

前端 未结 5 506
清歌不尽
清歌不尽 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: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);
    }
    

提交回复
热议问题