leetcode 7.整数反转
2018-12-26 20:41
375 查看
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
[code]示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21
要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。
[code]//pop operation: pop = x % 10; x /= 10; //push operation: temp = rev * 10 + pop; rev = temp;
但是,这种方法很危险,因为当temp = rev * 10 + pop时会导致溢出。
2^31-1=2147483647,-2^31=-2147483648
[code]class Solution { public: int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) //正数溢出 return 0; if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) //负数溢出 return 0; rev = rev * 10 + pop; } return rev; } };
相关文章推荐
- 【LeetCode】- Reverse Integer(将一个整数反转)
- LeetCode Reverse Integer 反转整数
- LeetCode-7-反转整数-c# 版本
- leetcode 7. Reverse Integer整数反转
- leetcode-整数反转
- LeetCode 7. Reverse Integer(反转整数)
- LeetCode第七题--反转32位的整数
- leetcode——Reverse Integer 反转整数数字(AC)
- leetcode 7 使用字符串操作反转整数
- leetcode的python实现 刷题笔记7: 反转整数
- Leetcode每日一道 -- 整数反转
- LeetCode-探索-初级-字符串-整数反转-java
- python实现leetcode-第七题-整数反转
- leetcode reverse Integer(反转整数)
- leetcode中文(一) #7反转整数,#77组合
- LeetCode7——Reverse Integer(将一个整数反转,注意溢出的处理)
- LeetCode7.整数反转 JavaScript
- LeetCode 第七题 反转整数
- [置顶] [LeetCode] Reverse Integer 整数反转
- 【leetcode】Reverse Integer整数反转----Java代码实现