Refer to a basic atoi
in C:
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != ''; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
Which translates into the Python:
def atoi(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
Test it:
>>> atoi('123456789')
123456789
If you want to accommodate an optional sign and whitespace the way that 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 exceptions and you are there!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…