LeetCode騰訊精選練習50——第二天
阿新 • • 發佈:2021-01-15
題目7:整數反轉
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉
題解:
class Solution:
def reverse(self, x: int) -> int:
if x>0:
a = str(x)
else:
a = str(-x)+'-'
a = int(a[::-1])
if a>=-2**31 and a<=2**31-1:
return a
else:
return 0
執行結果:
題目8:字串轉換整數
請你來實現一個 atoi 函式,使其能將字串轉換成整數
題解:
class Solution:
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
·使用正則表示式 ^:匹配字串開頭,[+-]:代表一個+字元或-字元,?:前面一個字元可有可無,\d:一個數字,+:前面一個字元的一個或多個,\D:一個非數字字元
執行結果:
題目9:迴文數
判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數
題解:
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if x == x[::-1]:
return True
else:
return False
執行結果: