LeetCode Reverse Integer
2014-06-24 14:34
357 查看
class Solution { public: int reverse(int x) { bool neg = x < 0; long long num = x; if (neg) num = -num; long long out = 0; while (num) { out = out * 10 + num % 10; num /= 10; } if (neg) return -out; return out; } };
再水
第二轮:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
用int来做:
class Solution { public: int reverse(int x) { int val = 0; int pos_threshold = INT_MAX/10; int neg_threshold = INT_MIN/10; bool positive = x >= 0; while (x) { int d = x % 10; if (positive) { if (val > pos_threshold) { val = 0; break; } } else { if (val < neg_threshold) { val = 0; break; } } val = val * 10 + d; x = x / 10; } return val; } };
因为是数字逆转,原来的输入数据也是在int范围内,所以如果数字长度是10位则第一位也只能是1或者2,所以只需判断前一次的结果值是否比threshold大/小就行
相关文章推荐
- LeetCode编程练习 - Reverse Integer学习心得
- Leetcode Reverse Integer
- LeetCode Reverse Integer
- Leetcode:Reverse Integer ,整数反转
- LeetCode:Reverse Integer
- LeetCode之Reverse Integer
- leetcode: reverse-integer
- LeetCode之Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : 7 Reverse Integer C++
- leetcode 7 Reverse Integer
- LeetCode-7(Reverse Integer)
- LeetCode (Easy Part) Reverse Integer
- leetcode Reverse Integer
- 【leetcode】Reverse Integer整数反转----Java代码实现
- Reverse Integer LeetCode 第七题
- 2---LeetCode【Reverse Integer】|C语言|总结
- leetcode: Reverse Integer
- leetcode Reverse Integer & Palindrome Number