[LeetCode]easy - Reverse Integer - python
阿新 • 來源:網路 • 發佈:2022-12-06
Problem Description:
Given a signed 32-bit integerx, returnxwith its digits reversed. If reversingxcauses the value to go outside the signed 32-bit integer, then return0.
題目要求反轉整數中的數字。
思路一:
首先判斷原數字的正負,用flag記錄一下。通過迴圈對10取餘得到尾部數字,一步步乘10構造新的翻轉後的整數。最後判斷結果是否溢位,若溢位則輸出0.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
flag = 1
else:
flag = -1
x = abs(x)
x_new = 0
while(x):
x_new = 10 * x_new + x % 10
x = x // 10
x_new = flag * x_new
return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0
結果如下。
![[LeetCode]easy - Reverse Integer - python [LeetCode]easy - Reverse Integer - python](https://img.796t.com/res/2022/12-06/19/ccd39bde749765c70d4b8c1ab71fdc1a.png)
思路二:
利用Python的字串切片 step=-1 操作來實現對整數的反轉,反轉後的字串轉換為整數後輸出。
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
flag = 1
else:
flag = -1
x = abs(x)
x_new = str(x)
x_new = int(x_new[::-1])
x_new = flag * x_new
return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0
結果如下:
![[LeetCode]easy - Reverse Integer - python [LeetCode]easy - Reverse Integer - python](https://img.796t.com/res/2022/12-06/19/a4505b5e3348f84555a0538c4d54cb98.png)
關於python切片的知識:
python切片物件的索引分為正索引和負索引兩部分
![[LeetCode]easy - Reverse Integer - python [LeetCode]easy - Reverse Integer - python](https://img.796t.com/res/2022/12-06/19/a52c55c64efa8ad8720d651f210ceb53.png)
完整的切片表示式包含兩個 “ : ”,用於分隔三個引數 ( start_index、end_index、step )。當只有一個 “ : ” 時,預設第三個引數step=1;當一個 “ :” 也沒有時,start_index=end_index,表示切取start_index指定的那個元素。
