python 实现字符串转整型

ord('0')=48,ord('A')=65,ord('a')=97
chr(65)='A'
def str2Int(s):
    s=s.strip()
    if len(s)==0:
        return 0
    dict_flag={'+':1,'-':-1}
    sum_,flag=0,1
    if s[0] in dict_flag:
        flag=dict_flag[s[0]]
    elif ord(s[0])>=48 and ord(s[0])<=57:
        sum_=sum_*10+(ord(s[0])-48)
    for i in s[1:]:
        if ord(i)>=48 and ord(i)<=57:
            sum_=sum_*10+(ord(i)-48)
    return sum_ if flag==1 else 0-sum_  

s=' -000013dd4'
str2Int(s)

 

 

方法二leetcode已提交代码:

def myAtoi( s):
        dict_num={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
        dict_flag={'+':1,'-':-1}
        s=s.strip()
        if len(s)==0 or (s[0] not in dict_num and s[0] not in dict_flag) :
            return 0
        sum,flag=0,1
        if s[0] in dict_flag:
            flag=dict_flag[s[0]]
        else:
            sum=dict_num[s[0]]
        for d in s[1:]:
            if d in dict_num:
                sum=sum*10+dict_num[d]
            else:
                break
        digit=sum*flag
        if digit >2**31-1:
            digit=2**31-1
        elif digit<-(2**31):
            digit=-(2**31)
        return digit

 

posted @ 2017-12-21 16:51  光彩照人  阅读(1380)  评论(0编辑  收藏  举报