Skip to content

Instantly share code, notes, and snippets.

@roxsula
Created December 12, 2018 21:54
Show Gist options
  • Save roxsula/3f2f0f6f41c400dbb7aac675e132b873 to your computer and use it in GitHub Desktop.
Save roxsula/3f2f0f6f41c400dbb7aac675e132b873 to your computer and use it in GitHub Desktop.
convert a string to integer without int() when the string is alphanumeric convert until find the first letter
def atoi(s):
integer = 0
sign = 1
s0 = s[0]
if s0 in '+-':
s = s[1:]
if s0 == '-':
sign = -1
for d in s:
if '0' <= d <= '9':
integer=integer*10 + ord(d) - ord('0')
else:
break
return sign*integer
#Examples
#print(atoi('-123')) -> -123
#print(atoi('+123')) -> 123
#print(atoi('12a13')) -> 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment