I have managed to program it in such a way that it inverts the digits of a number not greater than 9999. How can I do it with any integer without having to take into account that restriction? I suspect 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;
}
Very simple, replace the landline calls you are making with a loop:
And repeat until there are no digits left in the original number:
It's hard not to be anchored to a constraint since C++ types have a limit, for example if you invert the number 2,147,483,647 you will cause an overflow of
int
, since precisely that value is the maximum that a signed integer can hold. It could be solved by using along long
whose maximum signed value is 9,223,372,036,854,775,807 (and which, when inverted, does not coincidentally exceed its value).If your platform doesn't support
long long
then your intuition is correct:With a string of characters you will not have the indicated limitation, so this code:
It will show 7463847412 whereas in the numeric version it would have caused overflow.