8. String to Integer (atoi) [easy] (Python)
来源:互联网 发布:学java好还是安卓好 编辑:程序博客网 时间:2024/05/21 18:43
题目链接
https://leetcode.com/problems/string-to-integer-atoi/
题目原文
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.
题目翻译
实现“atoi”函数,将字符串转换成整数。
提示:请仔细考虑所有可能的输入情况。
思路方法
通过试错可以总结出要注意的四个点:
- 输入字符串为空、或其他不合法情况,返回0;
- 字符串开头的空格要在预处理中删掉;
- 处理可能出现的正负号“+”,“-”,正负号只能出现一次;
- 超出整数范围的值取整数范围的边界值。
思路一
按照上面要注意的点,比较可读的解法如下。
代码
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ if not str: return 0 str = str.strip() number, flag = 0, 1 if str[0] == '-': str = str[1:] flag = -1 elif str[0] == '+': str = str[1:] for c in str: if c >= '0' and c <= '9': number = 10*number + ord(c) - ord('0') else: break number = flag * number number = number if number <= 2147483647 else 2147483647 number = number if number >= -2147483648 else -2147483648 return number
思路二
用正则表达式来简化上面的过程。
代码
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ str = str.strip() try: res = re.search('(^[\+\-]?\d+)', str).group() res = int(res) res = res if res <= 2147483647 else 2147483647 res = res if res >= -2147483648 else -2147483648 except: res = 0 return res
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52053932
0 0
- 8. String to Integer (atoi) [easy] (Python)
- 8. String to Integer (atoi) Leetcode Python
- 【LeetCode】【Python】8. String to Integer (atoi)
- Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]
- Easy-题目67:8. String to Integer (atoi)
- Leetcode 8. String to Integer (atoi) (Easy) (cpp)
- Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]
- Leetcode[easy] - String to Integer (atoi)
- Easy 8题 String to Integer (atoi)
- String to Integer (atoi)(python)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 线性表(java)
- CR1000编程系列02 HelloWorld
- 从Hadoop到Spark的架构实践
- dubbo用途介绍
- node.js项目中的package.json
- 8. String to Integer (atoi) [easy] (Python)
- mysql 的一些基本操作
- PB学习中遇到的函数
- POJ3620Avoid The Lakes(DFS)
- 【OpenJudge】c语言_计算2的幂
- Studio中的项目接入百度地图sdk后,地图不能正常显示及出现 errorcode: 230 uid: -1 appid -1 msg: APP Scode码校验失败 问题的解决方法
- 别猜白块滑动效果实现
- 【NYOJ58】最小步数
- Django session