leetcode题目讲解(Python):字符串转整数 (atoi)
2024-09-07 07:00:40
分析这道题,输入数据有如下几种情况:
第一类:输入字符串无法转换为整数
这一类包含以下几种情况:
- 输入字符串为空
- 开头字符为数字、符号(+,-)、空格以外的字符
- 有多个加减符号的字符串
- 符号没有紧跟数字
- 字符串中没有数字
以上这几种情况直接返回 0
第二类: 输入字符串部分可以转换
这类情况中,数字后如出现其他不是数字的字符,那么该符号出现位置后的所有字符无效
第三轮: 可以全部转换
这类该怎么转就怎么转
参考代码如下:
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
raw_str = str
# set of valid
valid_set = {
'', '', '', '', '', '', '', '', '', '', '+', '-', ' '
}
# set of num
num_set = {'', '', '', '', '', '', '', '', '', ''}
# set of sign
sign_set = {'+', '-'}
# set of space k = # current location
m = # the number of signs
p = # the last space location
n = # the last signs location
i = # the number of 'num' temp_str = '' # case1: str is Null
if len(raw_str) == :
return # case2: illegal words at begining
if raw_str[] not in valid_set:
return for s in raw_str:
if s in sign_set:
# the sign after num is not valid
if i > :
break m = m +
n = k
# case3: if there are more than signs
if m > :
return
if s == ' ':
# the space after num is not valid
if i > :
break
p = k if s in num_set:
# case4: if the last sign location before last space location
if p > n and m > :
return
i = i +
temp_str = temp_str + s if s not in valid_set:
k = k +
break k = k + # case5: have no number in str:
if i == :
return
else:
# the num with sign
if m > :
temp_str = raw_str[n] + temp_str covert_int = int(temp_str) # overflow
if covert_int >= ** - :
return ** -
if covert_int <= (-**):
return (-**) return covert_int # test
s = Solution()
print(s.myAtoi("-42"))
参考:
最新文章
- FeWeb基础之JavaScript简介
- from xml
- setuptools,pip,install,UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte.原因和解决方案
- 计时器Chronometer和时钟(AnalogClock和DigitalClock)
- 《C++ primer》--第9章
- Android使用的开发MediaRecorder录制视频
- JAVA模拟各种请求方式访问RESTFUL
- 【解决办法】糟糕,我的电脑只有IE64位浏览器能上网,其他软件都上不了网
- 让magento的validate验证hidden field
- Microsoft.AspNetCore.Routing路由
- wamp的安装使用(转)
- Loadrunner常见错误处理方法
- spaCy is a library for advanced natural language processing in Python and Cython:spaCy 工业级自然语言处理工具
- Java线程之 InterruptedException 异常
- 性能测试 查看Android APP 帧数FPS的方法
- Win7系统分区提示会把选定的基本磁盘转化为动态磁盘
- Python游戏编程(Pygame)
- nvm+nodejs+npm
- Establish a website in 5 minutes
- jieba分词(3)