Several methods of conversion are not included here symbol '-', spaces, and other numbers not letters, not including the decimal point, on Leetcode Question 8 including these. The method herein is only applicable to similar to '12356' into a digital 12356.
Method 1: Use the function str
Int function can not be used, we can identify with 0-9 str function of each digital representation of characters
def atoi(s): s = s[::1] # 将s反转 num=0 for i,v in enumerate(s): for j in range(0,10): if v ==str(j): num+=j*(10**i) return num
Method 2: Using ord function
Using the ord function to find the ASCII code for each character in the ASCII code minus 0 is determined for each bit of digital
print (words ( ' 1 ' )) # 49 print (words ( ' 0 ' )) # 48
def atoi2(s): s = s[::1] num = 0 for i,v in enumerate(s): num+=(ord(v)-ord('0'))*(10**i) return num
Method three: eval function using
Function eval function is to serve as a valid string str evaluate expressions and return the results. Every character configured using the expression 1 multiplied and then converted to digital eval function to obtain a number for each character.
def atoi3(s): s = s[::1] num = 0 for i,v in enumerate(s): t = '%s *1'%v n = eval(t) num+=n*(10**i) return num