Reverse Integer
程序员文章站
2024-03-22 14:04:22
...
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
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2 ^ 31 ,2 ^ 31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Python代码:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
str_x = str(abs(x))
result = int(str_x[::-1])
if x < 0 :
result *= -1
if (result > 2**31 or result < -(2**31-1)) :
return 0
return result
思路:
取绝对值 , 转化为字符串 , 逆序 , 再转化为数字 , 判断是否溢出
上一篇: 数组-7-LeetCode 27题 -> 移除元素
下一篇: 面向对象基础