LeetCode 7. Reverse Integer(数学)
- By Scarb
- Scarb’s Blog
Tags:
- Math
问题描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解题思路
题意是将一个整数转置输出。提示:转置输出的数溢出时返回0.
所以要处理一下转置后的数溢出的特殊情况,这里包括了正溢出和负溢出。
参考代码
#include <iostream>
using namespace std;
class Solution {
public:
int reverse(int x) {
int num = 0;
while (x)
{
if (abs(num) > INT_MAX / 10 || // 处理溢出
(abs(num) == INT_MAX / 10 && abs(x) % 10 > INT_MAX % 10))
return 0;
num = num * 10 + x % 10;
x /= 10;
}
return num;
}
};
int main()
{
int i = 123;
Solution sl = Solution();
cout << sl.reverse(123) << endl;
cout << sl.reverse(-123) << endl;
cout << sl.reverse(103) << endl;
cout << sl.reverse(120) << endl;
cout << sl.reverse(1000000003) << endl;
cout << sl.reverse(-1000000003) << endl;
system("pause");
return 0;
}