leetcode 腾讯精选练习(50 题)4.整数反转
2019-05-13 21:13
573 查看
原题目
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123Output: 321Example 2:
Input: -123Output: -321Example 3:
Input: 120Output: 21Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路
将整数转换为字符串,正数时直接反转,负数时反转除负号之外的字符串,再将反转后的字符串转换为整型。如果整形数大于
2^32-1或小于
-2^32返回0。
python 整形
第一遍解法
# Runtime: 52 ms, faster than 56.39% of Python3# Memory Usage: 13.5 MB, less than 5.71% of Python3class Solution:def reverse(self, x):s = str(x)ans = 0if s[0] == '-': # 负数时反转除负号之外的字符串s_reverse = '-' + s[1:][::-1]ans = int(s_reverse)else: # 正数时直接反转ans = int(s[::-1])if ans < -2**31 or ans > 2**31-1:return 0else:return ans
网上好的解法
# 先除这个数的绝对值保留符号,再用字符串逆序这个数的绝对值# bit_length() 返回二进制数的位数,判定是否越界# Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zerosclass Solution:def reverse(self, x):r = x // max(1, abs(x)) * int(str(abs(x))[::-1])return r if r.bit_length() < 32 or r == -2**31 else 0
//javapublic int reverse(int x) {long rev= 0;while( x != 0){rev= rev*10 + x % 10;x= x/10;if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)return 0;}return (int) rev;}
//java 不使用长整数public int reverse(int x) {int prevRev = 0 , rev= 0;while( x != 0){rev= rev*10 + x % 10;if((rev - x % 10) / 10 != prevRev){return 0;}prevRev = rev;x= x/10;}return rev;}
自己可以改进的地方
最简代码
获得的思考
相关文章推荐
- leetcode NO.7 整数反转 腾讯精选练习50
- leetcode 腾讯精选练习(50 题)26.删除排序数组中的重复项
- LeetCode刷题第一天 第7题整数反转 腾讯50题
- leetcode 腾讯精选练习(50 题)16.最接近的三数之和
- leetcode NO.2两数相加 腾讯精选练习50
- leetcode 腾讯精选练习(50 题)6.回文数
- leetcode 腾讯精选练习(50 题)33.搜索旋转排序数组
- leetcode 腾讯精选练习(50 题)15.三数之和
- leetcode 腾讯精选练习(50 题)43.字符串相乘
- leetcode腾讯精选50-003
- leetcode 腾讯精选50
- leetcode腾讯精选50-015
- leetcode腾讯精选50-008
- leetcode腾讯精选50-021
- leetcode腾讯精选50-016
- LeetCode 7 :Reverse Integer ---- 反转int整数
- LeetCode 7. Reverse Integer(反转整数)
- LeetCode 7. Reverse Integer(整数反转)
- 【LeetCode】 反转整数
- Leetcode腾讯精选_编号:2 --python