Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created March 29, 2020 03:59
Show Gist options
  • Save nhudinhtuan/4269e03e42151abf4403eea557db8c08 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/4269e03e42151abf4403eea557db8c08 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
def in_range(num):
if num > 2 ** 31 - 1: return 2 ** 31 - 1
if num < -2**31: return -2**31
else: return num
#define state transition tables
states = {
# State (1) - initial state
1: { 'blank': 1, 'sign': 2, 'digit': 3 },
# State (2) - Signed - after finding +, -
2: { 'digit': 3 },
# State (3) - Integer
3: { 'digit': 3 },
}
# begin with initial state
current_state = 1
val = 0
sign = 1
for c in str:
if c == ' ':
c_type = 'blank'
elif c in '+-':
c_type = 'sign'
elif c in '0123456789':
c_type = 'digit'
else:
c_type = 'else'
# if we can not move on, we end it here
if c_type not in states[current_state]:
break
# process number
if c_type == 'sign':
sign = 1 if c == '+' else -1
elif c_type == 'digit':
val = val * 10 + int(c)
# move to next state
current_state = states[current_state][c_type]
return in_range(sign * val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment