文章目录
LeetCode】7,整数反转。 难度等级:中等(其实很简单)。
一、题目
二、我的解法
我的思路中规中矩,很容易理解:
class Solution:
def reverse(self, x: int) -> int:
MIN = -2 ** 31
MAX = 2 ** 31 - 1
# flag 用于区分正数和负数,首先将x均转为正数
flag = 1
if x < 0:
flag = -1
x *= -1
# 例子:当x=120时,ans=21;因此先将120转为12
if x % 10 == 0:
x = x // 10
# 个位数直接返回
if x < 10:
return flag * x
# 正整数反转
ans = 0
while x > 0:
ans = ans * 10 + x % 10
x = x // 10
if ans < MIN or ans > MAX:
ans = 0
return flag * ans
三、知识点:正整数的反转
数字反转是 LeetCode 中常见的问题,一定要熟练掌握。代码非常简单:
ans = 0
while x > 0:
ans = ans * 10 + x % 10
x = x // 10
"""
若 x = 1234, 则 ans = 4321
ans = 0 * 10 + 1234 % 10 = 0 + 4 = 4 , x = 1234 // 10 = 123 > 0
ans = 4 * 10 + 123 % 10 = 40 + 3 = 43, x = 123 // 10 = 12 > 0
ans = 43 * 10 + 12 % 10 = 430 + 2 = 432, x = 12 // 10 = 1 > 0
ans = 432 * 10 + 1 % 10 = 4320 + 1 = 4321, x = 1 // 10 = 0 = 0,结束循环
"""