Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
41 lines (34 loc) · 1.38 KB

File metadata and controls

41 lines (34 loc) · 1.38 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
class Solution:
def myAtoi(self, input: str) -> int:
sign = 1
result = 0
index = 0
n = len(input)
INT_MAX = pow(2, 31) - 1
INT_MIN = -pow(2, 31)
# Discard all spaces from the beginning of the input string.
while index < n and input[index] == " ":
index += 1
# sign = +1, if it's positive number, otherwise sign = -1.
if index < n and input[index] == "+":
sign = 1
index += 1
elif index < n and input[index] == "-":
sign = -1
index += 1
# Traverse next digits of input and stop if it is not a digit.
# End of string is also non-digit character.
while index < n and input[index].isdigit():
digit = int(input[index])
# Check overflow and underflow conditions.
if (result > INT_MAX // 10) or (
result == INT_MAX // 10 and digit > INT_MAX % 10
):
# If integer overflowed return 2^31-1, otherwise if underflowed return -2^31.
return INT_MAX if sign == 1 else INT_MIN
# Append current digit to the result.
result = 10 * result + digit
index += 1
# We have formed a valid number without any overflow/underflow.
# Return it after multiplying it with its sign.
return sign * result
Morty Proxy This is a proxified and sanitized view of the page, visit original site.