Question 7: Integer Reversal
Given a 32-bit signed integer, you need to reverse the digits on each of the integers.
Solution:
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
Running result:
Topic 8: Convert string to integer.
Please implement an atoi function to convert a string to an integer.
Solution:
class Solution:
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
·Use regular expression ^: match the beginning of the string, [+-]: represents a + character or-character, ?: the preceding character is optional, \d: a number, +: one or more of the preceding character A, \D: a non-numeric character
·max(min(number, 2 31-1), -2 31) is used to prevent the result from out of bounds.
Running result:
Question 9: Palindrome number
Determine whether an integer is a palindrome number. The palindrome number refers to the same integer in both positive order (from left to right) and reverse order (from right to left).
Solution:
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if x == x[::-1]:
return True
else:
return False
operation result: