[LeetCode] Reverse Integer 解题报告
来源:互联网 发布:大汉主义知乎 编辑:程序博客网 时间:2024/05/19 16:05
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: 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?
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).
» Solve this problem
[解题思路]
如果是用字符串来逆序的话,需要考虑0的特殊性,但是如果直接用一个integer来滚动生成的话,0就不是问题了。
当然,溢出的问题是存在的,所以return -1。
[Code]
1: int reverse(int x) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int lastDigit = 0;
5: int result = 0;
6: bool isNeg = x>0? false:true;
7: x = abs(x);
8: while(x>0)
9: {
10: lastDigit = x%10;
11: result = result*10 + lastDigit;
12: x = x/10;
13: }
14: if(result<0) return -1;
15: if(isNeg)
16: result *=-1;
17: return result;
18: }
Version 2, Refactor code, 3/5/2012
Rethink for a while. And actually, we don’t need to use special logic to handle ‘+’ and ‘-‘, because the sign can be kept during calculating. Only 8 lines can resolve this problem.
1: int reverse(int x) {
2: int newN =0, left =0;
3: while(x != 0)
4: {
5: left = x%10;
6: newN = newN*10 + left;
7: x = x/10;
8: }
9: return newN;
10: }
0 0
- LeetCode解题报告---Reverse Integer
- LeetCode-Reverse Integer-解题报告
- [LeetCode] Reverse Integer 解题报告
- [LeetCode] Reverse Integer 解题报告
- [LeetCode 解题报告] Reverse Integer
- [leetcode] 7. Reverse Integer 解题报告
- LeetCode 7 Reverse Integer 解题报告
- [Leetcode] 7. Reverse Integer 解题报告
- leetcode解题报告7. Reverse Integer
- [LeetCode 解题报告]007.Reverse Integer
- [leetcode]7. Reverse Integer@Java解题报告
- Reverse Integer解题报告
- Reverse Integer 解题报告
- LeetcodeProblem7 Reverse Integer解题报告
- 【LeetCode】Reverse Integer解题笔记
- 【Leetcode】7.Reverse Integer 解题
- [Leetcode]解题文档- Reverse Integer
- LeetCode解题-#7-Reverse Integer
- [LeetCode] Remove Duplicates from Sorted Array II 解题报告
- [LeetCode] Remove Duplicates from Sorted List 解题报告
- [LeetCode] Remove Element 解题报告
- [LeetCode] Remove Nth Node From End of List 解题报告
- [LeetCode] Restore IP Addresses 解题报告
- [LeetCode] Reverse Integer 解题报告
- [LeetCode] Reverse Linked List II 解题报告
- [LeetCode] Reverse Nodes in k-Group 解题报告
- [LeetCode] Roman To Integer 解题报告
- [LeetCode] Rotate Image 解题报告
- [LeetCode] Rotate List 解题报告
- [LeetCode] Scramble String 解题报告
- [LeetCode] Search for a Range 解题报告
- 使用flume thrift source的一点心得