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;
}
本文介绍了一个简单的整数反转算法,并提供了C++实现代码。该算法能够处理正数、负数及溢出情况,通过判断反转后的最后一位数字是否发生变化来检测溢出。文章通过实例演示了如何使用该算法。

被折叠的 条评论
为什么被折叠?



