7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321Example 2:
Input: -123
Output: -321Example 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 取整。
代码如下:
Python 用法总结
整型的 bit_length() 方法:
Last updated
Was this helpful?