forked from selfboot/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
08_StringtoInteger.py
executable file
·48 lines (40 loc) · 975 Bytes
/
08_StringtoInteger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
MAX_INT = 2**31 - 1
MIN_INT = - 2**31
def myAtoi(self, strs):
""" We need to handle four cases:
1. discards all leading whitespaces
2. sign of the number
3. overflow
4. invalid input
"""
strs = strs.strip()
if not strs:
return 0
sign, i = 1, 0
if strs[i] == '+':
i += 1
elif strs[i] == '-':
i += 1
sign = -1
num = 0
while i < len(strs):
if strs[i] < '0' or strs[i] > '9':
break
if num > self.MAX_INT or (num * 10 + int(strs[i]) > self.MAX_INT):
return self.MAX_INT if sign == 1 else self.MIN_INT
else:
num = num * 10 + int(strs[i])
i += 1
return num * sign
"""
""
" 12a"
" a12"
" +12"
" +-12"
"2147483648"
"-2147483648"
"""