LeetCode50題第2天
阿新 • • 發佈:2021-01-13
LeetCode第7題: 整數反轉
- 本題比較簡單, 利用地板除和取模即可得出, 最後需要判斷是否溢位
class Solution: def reverse(self, x: int) -> int: i = 1 if x < 0: i = -1 x = -x mid = 0 while x > 0: mid = mid * 10 + x % 10 x //= 10 if mid < -(1 << 31) or mid > ((1 << 31) - 1) : return 0 return i * mid
LeetCode第8題: 字串轉換整數
- 使用strip()去掉空格, 如果是空字元返回0
- 使用分支結構逐層判斷即可
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip()
if s == "":
return 0
k = 0
flag = 0
if s[0] in {'+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}:
if s[0] >= '0' and s[0] <= '9':
k = 1
else:
k = 1
flag = 1
for i in range(1, len(s)):
if (s[i] >= '0' and s[i] <= '9') or s[i] == '.':
k += 1
else:
break ;
if (k <= 0) or (flag == 1 and k <= 1):
return 0
i = int(float(s[0:k]))
if i < -(1 << 31):
return -(1 << 31)
if i > ((1 << 31) -1):
return ((1 << 31) - 1)
return i
LeetCode第9題: 迴文數
- 如果是負數直接返回False
- 如果是正數, 反轉比較即可
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
return int(str(x)[::-1]) == x