GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/008_String_to_Integer(atoi).py at master · pengaoao/leetcode

Expand file tree

/

008_String_to_Integer(atoi).py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
43 lines (40 loc) · 1.42 KB
/

008_String_to_Integer(atoi).py

Copy path

File metadata and controls

43 lines (40 loc) · 1.42 KB
Raw
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
42
43
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
sign = 1
max_int, min_int = 2147483647, -2147483648
result, pos = 0, 0
ls = len(str)
while pos < ls and str[pos] == ' ':
pos += 1
if pos < ls and str[pos] == '-':
sign = -1
pos += 1
elif pos < ls and str[pos] == '+':
pos += 1
while pos < ls and ord(str[pos]) >= ord('0') and ord(str[pos]) <= ord('9'):
num = ord(str[pos]) - ord('0')
if result > max_int / 10 or ( result == max_int / 10 and num >= 8):
if sign == -1:
return min_int
return max_int
result = result * 10 + num
pos += 1
return sign * result
# def myAtoi(self, s):
# #https://leetcode.com/discuss/83626/line-python-solution-eafp-instead-lbyl-easier-logic-beats-24%25
# try:
# s = s.lstrip() + '$' # remove leading spaces and append an end mark
# for i, ch in enumerate(s):
# if not (ch in '+-' or '0' <= ch <= '9'):
# result = int(s[:i])
# return -2 ** 31 if result < -2 ** 31 else 2 ** 31 - 1 if result > 2 ** 31 - 1 else result
# except:
# return 0
if __name__ == '__main__':
# begin
s = Solution()
print s.myAtoi("+-2")
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.