7. Reverse Integer
一、问题描述
Reverse digits of an integer.
**Have you thought about this?**Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
二、输入输出
Example1: x = 123, return 321
Example2: x = -123, return -321
三、解题思路
Integer To String
- 首先单独处理0的情况,防止对正负判断造成影响。其实也没啥影响,不过还是喜欢单独处理特殊情况。
- 然后记录下原输入是正数还是负数,并把x求绝对值。使用stringstream把abs(x)转换成string。
- 要求把int反转,那么现在的最高位翻转后就是个位,反转前的个位就变成了最高位。依次遍历string 把每一位的值按照权重加起来求和。主要结果一定要使用long来保存,避免int越界的问题。
- 最后还原原来的正负符号。并判断是否越界,包括超过最大值或者小于最小值。INT_MAX INT_MIN只能说不能更方便。
class Solution {
public:
int reverse(int x) {
if(x == 0)return 0;
bool isPositive;
if(x < 0)isPositive = false;
else isPositive = true;
stringstream ss;
ss << abs(x);
string str = ss.str();
long ret = 0;
for (int i = 0, n = str.size(); i < n; ++i) {
ret += (str[i] - '0') * pow(10, i);
}
ret = isPositive ? ret : (-1)*ret;
if(ret > INT_MAX || ret < INT_MIN){
ret = 0;
}
return static_cast<int>(ret);
}
};