Created
December 12, 2018 21:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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