Skip to content

Latest commit

 

History

History
32 lines (30 loc) · 716 Bytes

008.md

File metadata and controls

32 lines (30 loc) · 716 Bytes

8. String to Integer

Solution 1

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        s = str.strip()
        if len(s) == 0:
            return 0
        flag = 1
        if s[0] in ["+", "-"]:
            if s[0] == "-":
                flag = -1
            s = s[1:]
        ans = 0
        for c in s:
            if c >= "0" and c <= "9":
                ans = ans * 10 + ord(c) - ord("0")
            else:
                break
        ans *= flag
        if ans < -2 ** 31:
            return -2 ** 31
        if ans > 2 ** 31 - 1:
            return 2 ** 31 - 1
        return ans