diff --git a/1-100q/8.py b/1-100q/8.py index 1c91666..624bd84 100644 --- a/1-100q/8.py +++ b/1-100q/8.py @@ -1,38 +1,34 @@ -class Solution: - def myAtoi(self, str): - """ - :type str: str - :rtype: int - """ - str = str.strip() - number = "" - - - for x in str: - if x.isalpha() and number == "": - return 0 - elif x.isalpha(): - break - elif x == ".": - break - elif x == " ": - break - elif (x == "+" or x == "-") and number == "": - number = number + x - elif (x == "+" or x == "-") and number != "": - break - elif (x == "+" or x == "-") and (number[-1] == "+" or number[-1] == "-"): - return 0 - elif (x == "+" or x == "-") and ("+" in number or "-" in number): - break - elif x.isdigit(): - number = number + x - if number == "" or number == "+" or number == "-": - return 0 +def myAtoi(s: str) -> int: + s = s.lstrip() + + if not s: + return 0 + + # Determine sign + sign = 1 + if s[0] == '-': + sign = -1 + s = s[1:] + elif s[0] == '+': + s = s[1:] + + # Convert the number + result = 0 + for char in s: + if char.isdigit(): + result = result * 10 + int(char) else: - if int(number) > ((2**31)-1): - return (2**31)-1 - elif int(number) < -(2**31): - return -(2**31) - else: - return int(number) \ No newline at end of file + break + + # Apply sign + result *= sign + + max = 2**31 - 1 + min = -2**31 + + if result > max: + return max + if result < min: + return min + + return result