[Leetcode] Reverse Integer
来源:互联网 发布:古墓丽影9a卡优化补丁 编辑:程序博客网 时间:2024/05/17 04:30
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
[思路及要点]
1. 很多题解开辟isNegative标志,在最后将结果根据标志进行处理是否要*1,其实这里是不需要的,负号对于计算的结果没有影响。
2. 对于溢出的处理,虽然测试样例没有包含。使用long long存储结果,一旦越界及时跳出。
[代码]
class Solution {public: int reverse(int x) { long long res = 0; while (x) { res = res * 10 + x % 10; if (res > INT_MAX || res < INT_MIN) return -1; x /= 10; } return res; }};
从今天开始,伴随着自己的第二轮跳槽准备,我将会把之前的所有代码重新优化并且提供解题思路,欢迎大家参与讨论!
11/02/2014
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: 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: Reverse Integer
- Oracle重做日志文件--转载
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Oracle 跟踪方法--转
- [Leetcode] Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- [Leetcode] Reverse Integer
- [Leetcode] Search a 2D Matrix
- [Android]点击外层lyout控件改变内层控件颜色
- [Leetcode] Search for a Range
- [Leetcode] Same Tree
- [Leetcode] Valid Parentheses
- [Leetcode] Validate Binary Search Tree
- asp.net 页面生命周期
- C# LIST 使用泛型