剑指 Offer 67. 把字符串转换成整数
作者:互联网
思路:模拟,排除边界情况
Python:
class Solution: def strToInt(self, str: str) -> int: if not str or (len(str)==1 and (str[0]<'0' or str[0]>'9')): return 0 str=str.strip() count=len(str) digit_flag=False for i in range(len(str)): if str[i]=='-' or str[i]=='+': if not digit_flag: continue else: count=i break elif (str[i]>='0' and str[i]<='9'): digit_flag=True continue else: count=i break try: if str[0] == '-': if str[1]>'9' or str[1]<'0': return 0 try: tmp_int=int(str[1:count]) res=0-tmp_int except: tmp_int=int(str[1:]) res=0-tmp_int elif str[0]=='+': if str[1]>'9' or str[1]<'0': return 0 try: res=int(str[1:count]) except: res=int(str[1:]) elif str[0]>='0' and str[0]<='9': try: tmp_int=int(str[:count]) res=tmp_int except: tmp_int=int(float(str)) res=tmp_int else: return 0 except: return 0 if res>2**31-1: return 2**31-1 elif res<(-2)**31: return (-2)**31 else: return res
标签:转换成,elif,return,Offer,digit,len,flag,str,67 来源: https://www.cnblogs.com/tiuyoaix/p/16171935.html