您的位置:首页 > 其它

leetcode 腾讯精选练习(50 题)4.整数反转

2019-05-13 21:13 573 查看

原题目

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123Output: 321

Example 2:

Input: -123Output: -321

Example 3:

Input: 120Output: 21

Note:
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;}

自己可以改进的地方

最简代码

获得的思考

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: