题目描述:
题解:
1.去除str多余空格。
2.首先判断str[0]弟一个字符是否合法,如果str[0]是数字,正负号,则合法,否则直接返回0.
3.flag记录数字正负,1为正,-1为负,zero_nums记录之前是否出现过非0数字,用于去掉多余先导0。
4.从下标1开始对str遍历,将所有数字保存在nums数组中,如果str[i]出现小数点或字母,i位置之后的数字都视为无效。
5.先将nums中保存的数字转为字符串形式判断是否超界,如果没有则将其转为整型数字并返回。
class Solution: def strToInt(self, str: str) -> int: str = str.strip() if len(str) == 0: return 0 flag = 0 nums = [] zero_flag = 0 if str[0] >= '0' and str[0] <= '9': nums.append(str[0]) if str[0] != '0': zero_flag = 1 if (str[0] >= '0' and str[0] <= '9') or str[0] == '+': flag = 1 elif str[0] == '-': flag = -1 else: return 0 for i in range(1, len(str)): if str[i] >= '0' and str[i] <= '9': if str[i] != '0': nums.append(str[i]) zero_flag = 1 if str[i] == '0' and zero_flag == 1: nums.append(str[i]) else: break numstr = "".join(nums) if flag == 1 and (len(numstr) > 10 or (len(numstr) == 10 and numstr >= "2147483647")): return 2147483647 elif flag == -1 and (len(numstr) > 10 or (len(numstr) == 10 and numstr >= "2147483648")): return -2147483648 mul = 1 result = 0 for i in range(len(nums) - 1, -1, -1): result = result + int(nums[i]) * mul mul = mul * 10 if flag == -1: result = -result return result