String to Integer (atoi)(python)
来源:互联网 发布:python股票交易策略 编辑:程序博客网 时间:2024/05/21 17:19
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
注意如果超出范围就返回最接近的 int 数。eg:2147483648 大于 INT_MAX(2147483647) ,就返回 2147483647 。
要注意几点:跳过前面的空格,\t,\n;范围界定
class Solution:
# @return an integerdef myAtoi(self, str):
str = str.strip()
if not str:
return 0
MAX_INT = 2147483647
MIN_INT = -2147483648
ret = 0
overflow = False
pos = 0
sign = 1
if str[pos] == '-':
pos += 1
sign = -1
elif str[pos] == '+':
pos += 1
for i in range(pos, len(str)):
if not str[i].isdigit():
break
ret = ret * 10 + int(str[i])
if not MIN_INT <= sign * ret <= MAX_INT:
overflow = True
break
if overflow:
return MAX_INT if sign == 1 else MIN_INT
else:
return sign * ret
0 0
- String to Integer (atoi)(python)
- 【LeetCode with Python】 String to Integer (atoi)
- 刷题-String to Integer (atoi)缺python
- 8. String to Integer (atoi) Leetcode Python
- 8. String to Integer (atoi) [easy] (Python)
- 【LeetCode】【Python】8. String to Integer (atoi)
- [LeetCode] String to Integer (atoi) Python
- 【Leetcode】【python】String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- swift 3.0变化点
- [iOS 自动打包]shell脚本使用-ipa_build 脚本使用
- 字典的基础操作
- Web开发中 前端路由 实现的几种方式和适用场景
- 最全动画系列教程-登录动画效果
- String to Integer (atoi)(python)
- 318. Maximum Product of Word Lengths
- Java Serializable(序列化)的理解和总结
- linux "-bash: telnet: command not found" telnet不是命令
- JSON里的大括号{}和中括号[]。(关于JSON的结构)
- HDU 1241 Oil Deposits【简单DPS搜索】
- iOS获取相册中所有图片
- java使用JNDI 获取weblogic配置的数据源 连接数据库
- 学习shell script