Skip to content

Commit c88c2b7

Browse files
committed
Init
1 parent d89af9c commit c88c2b7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Python/String_To_Int.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def toInt(s):
2+
"""
3+
:type str: str
4+
:rtype: int
5+
"""
6+
num = i = 0
7+
nums = "0987654321"
8+
s = s.strip(" ")
9+
if not s: return 0
10+
neg = s[0] == "-"
11+
if s[0] == "+" or neg: s = s[1:]
12+
if not s: return 0
13+
if s[0] != "-" and s[0] != "+" and s[0] not in nums: return 0
14+
while i < len(s) and s[i] in nums: i += 1
15+
if not i and s[i] not in nums: return 0
16+
num = int(s[:i]) if not neg else - 1 * int(s[:i])
17+
if num > (2**31) - 1: return (2 ** 31) - 1
18+
if num < -(2**31): return -1 * (2 ** 31)
19+
return num
20+

0 commit comments

Comments
 (0)