整数反转
class Solution:
def reverse(self, x: int) -> int:
ans=0
INTMAX10 = 214748364
INTMIN10 = -214748364
while x:
pop=x%10 if x>0 else x%-10
x=x//10 if x>0 else int(x/10)
if ans>INTMAX10 or (ans==INTMAX10 and pop>7):
return 0
if ans<INTMIN10 or (ans==INTMIN10 and pop<-8):
return 0
ans=ans*10+pop
return ans
Atoi字符串转换整数
INT_MAX = 2 ** 31 - 1
INT_MIN = -2 ** 31
class Automaton:
def __init__(self):
self.state = 'start'
self.sign = 1
self.ans = 0
self.table = {
'start': ['start', 'signed', 'in_number', 'end'],
'signed': ['end', 'end', 'in_number', 'end'],
'in_number': ['end', 'end', 'in_number', 'end'],
'end': ['end', 'end', 'end', 'end'],
}
def get_col(self, c):
if c.isspace():
return 0
if c == '+' or c == '-':
return 1
if c.isdigit():
return 2
return 3
def get(self, c):
self.state = self.table[self.state][self.get_col(c)]
if self.state == 'in_number':
self.ans = self.ans * 10 + int(c)
self.ans = min(self.ans, INT_MAX) if self.sign == 1 else min(self.ans, -INT_MIN)
elif self.state == 'signed':
self.sign = 1 if c == '+' else -1
class Solution:
def myAtoi(self, str: str) -> int:
automaton = Automaton()
for c in str:
automaton.get(c)
return automaton.sign * automaton.ans
回文数
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x%10==0 and x!=0):
return False
revNum=0
while x> revNum:
revNum=revNum*10+x%10
x//=10
return x==revNum or x==revNum//10