LeetCode OJ Reverse Integer
2015-03-23 00:14
330 查看
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?
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).
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?
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).
class Solution { public: int reverse(int x) { int positive = 1; if (x < 0) { positive = -1; x = -x; } long long int ans = 0; while (x) { ans = ans * 10 + x % 10; x /= 10; } return ans * positive; } };
相关文章推荐
- Leetcode Oj Reverse Integer
- 【leetcode】Reverse Integer(middle)☆
- 2---LeetCode【Reverse Integer】|C语言|总结
- leetcode002-数值处理Reverse Integer,Pow(x,n), atoi, Divide Two Integers
- LeetCode Reverse Integer 反转整数
- LeetCode 7 - Reverse Integer
- LeetCode 7 Reverse Integer 这道题被血虐
- 【python】【leetcode】【算法题目7—Reverse Integer】
- leetcode Reverse Integer java基本编程学习笔记(一)
- [LeetCode] Reverse Integer 解题报告
- LeetCode Reverse Integer
- LeetCode Reverse Integer
- Reverse Integer Leetcode 每日一题 ↖(^ω^)↗
- LeetCode Reverse Integer
- leetcode Reverse Integer 007
- LeetCode 7 Reverse Integer 这道题被血虐
- Leetcode 7 Reverse Integer 将整数逆转
- LeetCode : 7 Reverse Integer C++
- LeetCode Reverse Integer
- 《leetCode》:Reverse Integer