Refer to the base atoi in C:
int myAtoi(char *str) { int res = 0;
What translates to Python:
def atoi(s): rtr=0 for c in s: rtr=rtr*10 + ord(c) - ord('0') return rtr
Check this:
>>> atoi('123456789') 123456789
If you want to place an optional character and space, as int does:
def atoi(s): rtr, sign=0, 1 s=s.strip() if s[0] in '+-': sc, s=s[0], s[1:] if sc=='-': sign=-1 for c in s: rtr=rtr*10 + ord(c) - ord('0') return sign*rtr
Now add the exceptions and you are there!
source share