7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
解法
转成字符串后翻转再转回来。
python
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >= 0 else -1
res = int(str(abs(x))[::-1])
return res * sign if res.bit_length() < 32 else 0
使用数学方法,例如 n = 12345,res初始为 0,每次循环为 n 取模加上上次的 res 乘 10,n 每次除以 10 取整。
n = 12345
res = 0
res = 0 * 10 + 12345 % 10 = 5
n = 12345 // 10 = 1234
res = 5 * 10 + 1234 % 10 = 54
n = 1234 // 10 = 123
res = 54 * 10 + 123 % 10 = 543
n = 123 // 10 = 12
res = 543 * 10 + 12 % 10 = 5432
n = 12 // 10 = 1
res = 5432 * 10 + 1 % 10 = 54321
n = 1 // 10 = 0
代码如下:
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >= 0 else -1
x = abs(x)
res = 0
while x:
res = res * 10 + x % 10
x //= 10
return res * sign if res.bit_length() < 32 else 0
Python 用法总结
整型的 bit_length()
方法:
Help on method_descriptor:
bit_length(...)
int.bit_length() -> int
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
Last updated
Was this helpful?