分析这道题,输入数据有如下几种情况:

第一类:输入字符串无法转换为整数

这一类包含以下几种情况:

  1. 输入字符串为空
  2. 开头字符为数字、符号(+,-)、空格以外的字符
  3. 有多个加减符号的字符串
  4. 符号没有紧跟数字
  5. 字符串中没有数字

以上这几种情况直接返回 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"))
参考:
 
 
 
 
 

最新文章

  1. FeWeb基础之JavaScript简介
  2. from xml
  3. setuptools,pip,install,UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte.原因和解决方案
  4. 计时器Chronometer和时钟(AnalogClock和DigitalClock)
  5. 《C++ primer》--第9章
  6. Android使用的开发MediaRecorder录制视频
  7. JAVA模拟各种请求方式访问RESTFUL
  8. 【解决办法】糟糕,我的电脑只有IE64位浏览器能上网,其他软件都上不了网
  9. 让magento的validate验证hidden field
  10. Microsoft.AspNetCore.Routing路由
  11. wamp的安装使用(转)
  12. Loadrunner常见错误处理方法
  13. spaCy is a library for advanced natural language processing in Python and Cython:spaCy 工业级自然语言处理工具
  14. Java线程之 InterruptedException 异常
  15. 性能测试 查看Android APP 帧数FPS的方法
  16. Win7系统分区提示会把选定的基本磁盘转化为动态磁盘
  17. Python游戏编程(Pygame)
  18. nvm+nodejs+npm
  19. Establish a website in 5 minutes
  20. jieba分词(3)

热门文章

  1. java中四种权限修饰符区别
  2. nginx+rsync实现本地yum源以及公网yum源
  3. hexo更改主题
  4. Linu如何查看磁盘占用情况及处理办法
  5. Linux-firewall防火墙
  6. 蓝桥杯-基础练习 :java 数列排序问题
  7. 获取ul li的value的值
  8. springboot禁用内置Tomcat的不安全请求方法
  9. rhce 考试题目总结
  10. Kotlin中Range与异常体系剖析