MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / myAtoi

Method myAtoi

String/StringToInteger.py:68–111  ·  view source on GitHub ↗

:type str: str :rtype: int

(self, strs)

Source from the content-addressed store, hash-verified

66
67class Solution(object):
68 def myAtoi(self, strs):
69 """
70 :type str: str
71 :rtype: int
72 """
73 nums = '1234567890'
74 signs = '+-'
75
76 strs = strs.strip()
77
78 if not strs or len(strs) == 1 and strs in signs:
79 return 0
80
81 if strs[0] in signs:
82 sign = strs[0]
83 strs = strs[1:]
84 else:
85 sign = '+'
86
87 str_num = '0'
88 x = 0
89 for i in strs:
90 if i == ' ' and str_num == '0':
91 return 0
92 if i not in nums:
93 if sign == '+':
94 x = int(str_num)
95 else:
96 x = -int(str_num)
97 break
98 else:
99 str_num += i
100 else:
101 if sign == '+':
102 x = int(str_num)
103 else:
104 x = -int(str_num)
105
106 if x > 2**31-1:
107 return 2**31-1
108 elif x < -2**31:
109 return -2**31
110 else:
111 return x

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected