[LeetCode]69. Recerse Integer旋转整数
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
Subscribe to see which companies asked this question
解法1:使用to_string、std::reverse、stoll库函数。注意到旋转后可能溢出,因此设置临时变量时应该为long long,然后判断并处理。class Solution { public: int reverse(int x) { string s = to_string(x); if (s[0] == '-') std::reverse(s.begin() + 1, s.end()); else std::reverse(s.begin(), s.end()); long long n = stoll(s); if (n > INT_MAX || n < INT_MIN) return 0; return n; } };
解法2:先判断输入的正负,然后对绝对值处理,每次取末位相加,最后判断是否溢出。
class Solution { public: int reverse(int x) { long long res = 0; bool isNegative = false; if (x < 0) { x = -x; isNegative = true; } while (x > 0) { res *= 10; res += x % 10; x /= 10; } if (res > INT_MAX) return 0; return isNegative ? -res : res; } };
实际上不需要事先判断输入的正负,因为在取余的时候会自动包含进去,此时while循环的结束条件是x!=0。
class Solution { public: int reverse(int x) { long long res = 0; while (x != 0) { res *= 10; res += x % 10; x /= 10; } if (res > INT_MAX || res < INT_MIN) return 0; return res; } };
转载于:https://www.cnblogs.com/aprilcheny/p/4949933.html
- [LeetCode]69. Recerse Integer旋转整数
- [LeetCode] Integer to Roman 整数转化成罗马数字
- LeetCode——Reverse Integer(逆置一个整数)
- leetcode-13-罗马数字转整数(roman to integer)-java
- leetcode:String to Integer (atoi) 字符串转化成整数
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- [LeetCode] Number of 1 Bits & Reverse Integer - 整数问题系列
- leetcode第129周赛-1015. Smallest Integer Divisible by K,被K整除的最小整数
- leetcode-8-String to Integer (atop)字符串转整数
- LeetCode 8. String to Integer (atoi) (字符串到整数)
- LeetCode 7. Reverse Integer(整数反转)
- LeetCode 13. Roman to Integer 罗马数字转整数
- leetcode_7. Reverse Integer 反转整数的各个数字
- (LeetCode)Integer Replacement --- 整数替换
- LeetCode:第7题: 反转整数(reverse-integer)
- [LeetCode] String to Integer (atoi) 字符串转为整数
- leetcode8- String to Integer (atoi 字符串转整数)
- 每日一练之Reverse Integer[LeetCode No.7]-翻转整数
- 【leetcode】Reverse Integer整数反转----Java代码实现
- LeetCode | Reverse Integer(翻转整数)