LeetCode:7. Reverse Integer
程序员文章站
2022-07-15 14:39:11
...
题目:
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.
Answer:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sum = 0
n = 0
if x > 0:
flag = 1
else:
flag = -1
x = x * flag
lt = []
while x:
lt.append(x % 10)
x = int(x / 10)
n += 1
for i in lt:
sum += i * pow(10, n-1)
n -= 1
if sum > pow(2, 31) - 1 or sum < -pow(2, 31):
return 0
if flag == -1:
return -sum
else:
return sum
思路:
将数字拆开存入数组中,再组合成Reverse Interger,注意数字范围,最后加上正负判断。
上一篇: 7. reverse-integer
下一篇: 内存泄漏总结