c++ – How do I reverse the digits of any number?

Question:

I have managed to program it in such a way that it inverts the digits of a number no greater than 9999. How can I do it with any whole number without having to take that restriction into account? I suspect that I have to work with strings.

#include "stdafx.h"
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int reverse(int numb);

int main()
{

int x;
    cout << "Number: " << endl;
    cin >> x;

    cout << reverse(x) << endl;

    cin.ignore();
    cin.get();
    return 0;
}

int reverse(int numb)
{
    int m, c, d, u, newnumber;
    m = numb / 1000;
    c = (numb - (m * 1000)) / 100;
    d = (numb - ((m * 1000) + (c * 100))) / 10;
    u = (numb - ((m * 1000)+(c* 100)+( d * 10)));

    newnumber = (u * 1000 + d * 100 + c * 10 + m);
    return newnumber;
}

Answer:

Very simple, replace the fixed calls you are making with a loop:

  • You multiply the final number by 10
  • You take the least significant digit of the number to invest
  • Add that digit to the final number

And you repeat until there are no digits left in the original number:

int reverse(int numb)
{
  int newnumber = 0;
  while( numb != 0)
  {
    newnumber *= 10;
    newnumber += numb % 10;
    numb /= 10;
  }
  return newnumber;
}
Scroll to Top