Title Description
Converting a string to an integer (which implements the Integer. valueOf (string) function, but returns 0 if the string does not meet the number requirement) requires that the library function that converts an integer using a string cannot be used. The value is 0 or the string is not a valid number.The value is returned to 0.
Examples
input
+2147483647 1a33
output
2147483647 0
Title Description
This is a headache because the topic requires no library function. Then Baidu said it could convert strings into ASCII codes (decimal values). The conversion function is ord, which is the corresponding character returned, compared with the table http://ascii.911cha.com/.ASCII code, and Chr is just the opposite of ord, converting an integer to the corresponding character.
class Solution: def StrToInt(self, s): res,pos,mult = 0,1,1 ###resIs the initial return value; POS is a positive or negative tag; mult is a multiplier of digits, digits 1, 10, and 100if not s:#String emptyreturn res elif len(s)==1:#String length 1 is discussed separately.if 48 < ord(s) <= 57: return ord(s)-48 else: return 0 elif s[0]=='-' or s[0]=='+':#The string is preceded by a minus sign.if s[0]=='-' and s[1]!='0': pos = -1 s = s[1:] elif s[0]=='-' and s[1]=='0': return res elif s[0] =='+' and s[1]!='0': pos = 1 s = s[1:] elif s[0]=='+' and s[1]=='0': return res for i in range(len(s)-1,-1,-1):#String values are removed from negative strings.if '9' >= s[i] >= '0': res += (ord(s[i])-48)*mult mult = mult*10 else: return 0 return res*pos