题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
思考
为了避免溢出,先将int转为string,利用reverse函数将其反转,然后再将结果string转回int。是否溢出可以根据stoi抛出的异常来判断。
我的答案
c++
class Solution {
public:
int reverse(int x) {
stringstream ss;
string str;
ss << x;
ss >> str;
if (x > 0) std::reverse(str.begin(), str.end());
else std::reverse(str.begin()+1, str.end());
int resultInt;
try {
resultInt = stoi(str);
} catch(std::out_of_range) {
return 0;
}
return resultInt;
}
};
用时:22ms
由于方法较复杂(int转string再转int),所以用时较久,可以进行改进:
对于c++,负数进行取余运算的结果依然为负数。
class Solution {
public:
int reverse(int x) {
long long result = 0;
while(x) {
result = result * 10 + x % 10;
x /= 10;
}
if (result < INT_MIN || result > INT_MAX) return 0;
return result;
}
};
改进后用时:6ms