LeetCode # 7 整數反轉
思路 1
- 從最低位開始處理 使用到 % 10 // 10 等工具
- 注意符號
- 注意邊界情況
代碼 1
class Solution:
def reverse(self, x: int) -> int:
if( x > 0 ):
s = 1
else:
s = -1
x = abs(x)
res = 0
while(x > 0):
tmp = x % 10
res = res * 10 + tmp
x = x // 10
if(res > 2**31 - 1 or res < - 2 ** 31):
return 0
return res * s