1. 程式人生 > 其它 >【記錄】省選聯考2022遊記

【記錄】省選聯考2022遊記

思路:模擬,排除邊界情況

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