700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 判断字符为空_算法题:字符串转换整数 (atoi)

判断字符为空_算法题:字符串转换整数 (atoi)

时间:2020-04-29 02:15:33

相关推荐

判断字符为空_算法题:字符串转换整数 (atoi)

题目描述题解分析他人更优解

一、题目描述

二、题解

import mathclass 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:带只拖鞋去流浪

简书:带只拖鞋去流浪

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。