文章链接:https://leetcode.com/problems/reverse-integer/
Runtimes:14ms
1、问题
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
2、分析
不用额外的空间,逆序整数,溢出按0处理。
3、小结
边界处理采用了leetcode34的做法,题目比较简单。
4、实现
class Solution {
public:
bool check(int a, int b, bool f)
{
if (f)
{
if ((INT_MIN + b) / 10 > (0 - a))
return true;
}
else{
if ((INT_MAX - b) / 10 < a)
return true;
}
return false;
}
int reverse(int x) {
bool isMinus = false;
if(x < 0)
{
isMinus = true;
x = 0 - x;
}
int sum = 0;
while(x > 0)
{
if(check(sum, x % 10, isMinus))
return 0;
sum = sum * 10 + x % 10;
x /= 10;
}
return isMinus ? 0 - sum : sum;
}
};
5、反思
效果不错。
本文提供了一种解决LeetCode上逆序整数问题的有效方法,通过C++实现,考虑了整数溢出的情况,并针对特定边界情况进行了特别处理。
172

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



