1 class Solution: 2 def myAtoi(self, str: str) -> int: 3 i = 0 4 n = len(str) 5 if n==0: 6 return 0 7 while i<n and str[i]==' ': 8 i += 1 9 if i==n: 10 return 0 11 flag = 1 12 if str[i]=='-': 13 flag=-1 14 i += 1 15 elif str[i]=='+': 16 i +=1 17 intmax = 2**31 18 res = 0 19 while i<n and (str[i]>='0' and str[i]<='9'): 20 res =res*10+int(str[i]) 21 if res>intmax: 22 break 23 i +=1 24 res = res*flag 25 if flag==1: 26 if res>=intmax: 27 return intmax-1 28 else: 29 return res 30 else: 31 return res if res>intmax*flag else intmax*flag
9.判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
(note:python中只取整数部分://)
/:17/10 = 1.7
//:17//10 = 1
1 class Solution: 2 def isPalindrome(self, x: int) -> bool: 3 if x<0 or (x%10==0 and x!=0): 4 return False 5 tmp = 0 6 while(x>tmp): 7 tmp = tmp*10+x%10 8 x = x//10 9 return (x==tmp) or (x==(tmp//10))