难度:简单
知识点:数学
地址:https://leetcode-cn.com/problems/reverse-integer/
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
from config import MAX
from config import MIN
class Solution:
def reverse(self, x: int) -> int:
'''
弹出和推入数字
时间复杂度 O(logn)
空间复杂度 O(1)
执行用时 : 48 ms, 在Reverse Integer的Python3提交中击败了98.06% 的用户
内存消耗 : 13 MB, 在Reverse Integer的Python3提交中击败了99.21% 的用户
'''
ans = 0
rem = 10 if x > 0 else -10
while x != 0:
yu = x % rem
ans = ans * 10 + yu
x //= 10
if x < 0 and yu != 0:
x += 1
if ans > MAX or ans < MIN:
return 0
return ans
s = Solution()
assert s.reverse(-123) == -321
assert s.reverse(123) == 321
assert s.reverse(120) == 21