Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Need to pay attention to negative numbers.... and overflow case.
Here, the overflow case is handled neatly! If it is overflowed, the last digit wont be the same as before......
#include <iostream>
#include <algorithm>
using namespace std;
int reverse(int x) {
int i = 0;
bool negative = false;
if(x < 0) negative = true;
x = abs(x);
int res = 0;
while(x) {
int tmp = x % 10;
res = res * 10 + tmp;
if(res % 10 != tmp) return 0; // if overflowed, the last digit will sure be changed.
x = x / 10;
}
return negative ? -res : res;
}
int main(void) {
int num = -123;
cout << reverse(num) << endl;
}