- 题目描述
- 题解
- 分析
- 他人更优解
一、题目描述

二、题解
import math
class Solution:def myAtoi(self,str):str = str.strip() #去除字符串两边的空格if len(str) == 0: return 0 #如果字符串为空返回0if not str[0].isdigit() and str[0] != '-' and str[0] != '+': #判断第一个字符是否为数字或'-'/'+'return 0i,num_list = 1,[str[0]]while i<len(str): #遍历,遍历到不是数字退出if str[i].isdigit():num_list.append(str[i])i += 1else: breakif ''.join(num_list) == '-' or ''.join(num_list) == '+': return 0 #字符串只有'-'或'+'result = int(''.join(num_list))if result > math.pow(2,31)-1: return int(math.pow(2,31)-1) #超限elif result < math.pow(-2,31): return int(math.pow(-2,31)) #超限return result

三、分析
- 字符串去除两边空格:str.strip()
- 列表转字符串:''.join(list)
- 判断字符串是否为纯数字:str.isdigit()
四、他人更优解
使用了正则表达式

warning :未经授权,不得转载
有问题的小伙伴请在下方留言,喜欢就点个赞吧;关注我,带你一起写bug
CSDN:带只拖鞋去流浪
简书:带只拖鞋去流浪