【Leetcode】【python】String to Integer (atoi)
来源:互联网 发布:新手开淘宝店卖什么好 编辑:程序博客网 时间:2024/05/29 07:08
题目大意
写出函数,将str转为int
需要考虑所有可能的输入情况
解题思路
将情况都考虑进去
代码
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ INT_MAX = 2147483647 INT_MIN = -2147483648 result = 0 if not str: # 不是str返回0 return result i = 0 while i < len(str) and str[i].isspace(): # 判断空格 i += 1 sign = 1 # 若有‘-’结果相反数 if str[i] == "+": i += 1 elif str[i] == "-": sign = -1 i += 1 while i < len(str) and str[i] >= '0' and str[i] <= '9': if result > (INT_MAX - (ord(str[i]) - ord('0'))) / 10: return INT_MAX if sign > 0 else INT_MIN result = result * 10 + ord(str[i]) - ord('0') i += 1 return sign * result
总结
这里用ord()计算ascii的差值,如果直接int()那就等于把这题直接用内部函数解决了。
阅读全文
0 0
- 【LeetCode with Python】 String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- 【LeetCode】【Python】8. String to Integer (atoi)
- [LeetCode] String to Integer (atoi) Python
- 【Leetcode】【python】String to Integer (atoi)
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- MessageFormat使用时对单引号的处理方式
- Wasserstein GAN最新进展:从weight clipping到gradient penalty,更加先进的Lipschitz限制手法
- 从传统GAN到improved WGAN
- Perl 入门实战:JVM 监控脚本(下)
- 从PM到GAN——LSTM之父Schmidhuber横跨22年的怨念(文字版)
- 【Leetcode】【python】String to Integer (atoi)
- Face in Circle
- 返璞归真,运用Android广播机制来通知界面刷新
- 使用iptables的bpf match来优化规则集-HiPAC/ipset/n+1模型之外的方法
- 课本第三章java编程题
- AWS核心服务概览
- 生成对抗网络(GAN)相比传统训练方法有什么优势?(一)
- 知道这20个正则表达式,能让你少写1,000行代码
- luogu P1983 车站分级