【LeetCode】 反转整数
2018-10-17 23:29
288 查看
题目描述
补充一下复数除法及取余的问题:
负数除法
不管是正数还是负数都是向0取整的:10/4 = 2,10/(-4) = -2
负数取余
余数的绝对值 = 被除数绝对值%除数绝对值,余数符号与被除数符号一致
3%4 = 3 ; -3%4 = -3 ; -3%-4 = -3 ; 3%-4 = 3;
5%3 = 2 ; 5%-3 = 2 ;-5%-3 = -2 ; -5%3 = -2;
参考https://www.geek-share.com/detail/2702873192.html
解题思路
从个位往前每次取一位数,放入反转后的数中,记住这里取每一位数的数学方法!
[code]//pop operation: pop = x % 10; x /= 10; //push operation: temp = rev * 10 + pop; rev = temp;
但是,temp = rev * 10 + pop 可能会溢出,所以需要事先检查rev的大小(通过比较rev和 INT_MAX/10 的大小)
(开始我没注意到INT_MAX/10是整数,看了很久才看懂答案)
1)rev是正数
rev * 10 + pop > INT_MAX 时会溢出,记 INTMAX = 10 * k + r , k = INT_MAX/10,因为INT_MAX = 2147483647,所以r = 7
- rev < k,temp < INT_MAX
- rev == k,temp = 10 * k + pop,当pop > 7时,溢出
- rev > k,temp溢出
2) rev是负数
rev * 10 + pop < INT_MIN 时会溢出,记 INT_MIN = 10 * k + r , k = INT_MIN/10 (<0),因为INT_MIN = -2147483648,所以r = -8
- rev < k,temp < INT_MIN,溢出
- rev == k,temp = 10 * k + pop,当pop < -8 时,溢出
- rev > k,temp > INT_MIN
复杂度分析
时间复杂度:O(logx),因为x中约有 个有效数字
空间复杂度:O(1)
代码
[code]class Solution { public: int reverse(int x) { int rev = 0; int pop; while(x != 0){ 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; } };
执行时间前(1-67.37)%,还好吧毕竟是官方答案,刚发现LeetCode能看各个执行时间段的范例,嘻嘻好棒,明天再看
相关文章推荐
- LeetCode 7. Reverse Integer 整数反转
- 【LeetCode】- Reverse Integer(将一个整数反转)
- Leetcode7.整数反转(python3)
- 【菜鸡的LeetCode答案】【C#】7.反转整数
- LeetCode-Python-7. 整数反转
- [leetcode] Reverse Integer 反转一个整数
- leetcode-整数反转
- 【leetcode】7.整数反转
- (LeetCode)反转整数
- Leetcode Reverse Integer 反转整数
- LeetCode 7 :Reverse Integer ---- 反转int整数
- LeetCode - 7. 反转整数
- LeetCode Reverse Integer 反转整数
- (LeetCode)Reverse Integer --- 反转整数
- LeetCode第7题:整数反转 之 先从简单刚起(C++)
- LeetCode-7-反转整数-c# 版本
- [leetcode]反转整数
- [置顶] [LeetCode] Reverse Integer 整数反转
- leetcode 7. 反转整数(c++版)
- LeetCode 整数反转