【leetcode】8. String to Integer (atoi)
来源:互联网 发布:php注册登陆页面代码 编辑:程序博客网 时间:2024/06/07 22:59
问题描述:
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.
思路:
看似很简单的一道题,但是通过率很低(13.8)。原因是很难把所以情况都一次性考虑到。这道题能反应一个程序员的经验和缜密的逻辑。
需要考虑的输入情况有:1,空输入;2,字符串开头为“ ”;3,正负号;4,溢出。解决方案如下:
public int myAtoi(String str) { int index = 0, sign = 1, total = 0; //1. 空输入: if(str.length() == 0) return 0; //2. 以空字符开头: while(str.charAt(index) == ' ' && index < str.length()) index ++; //3. 正负号: if(str.charAt(index) == '+' || str.charAt(index) == '-'){ sign = str.charAt(index) == '+' ? 1 : -1; index ++; } while(index < str.length()){ int digit = str.charAt(index) - '0'; if(digit < 0 || digit > 9) break; //4:解决溢出问题; if(Integer.MAX_VALUE/10 < total || (Integer.MAX_VALUE/10==total && Integer.MAX_VALUE %10 < digit)) return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; total = 10 * total + digit; index ++; } return total * sign;}
1 0
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- LeetCode --- 8. String to Integer (atoi)
- LeetCode 8.String to Integer (atoi)
- [Leetcode] 8. String to Integer (atoi)
- [leetcode] 8.String to Integer (atoi)
- [LeetCode] 8.String to Integer (atoi)
- <LeetCode OJ> 8. String to Integer (atoi)
- leetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) LeetCode
- leetcode 8. String to Integer (atoi)
- leetcode 8. String to Integer (atoi)
- LeetCode OJ 8.String to Integer (atoi)
- Leetcode ☞ 8. String to Integer (atoi)
- 8. String to Integer (atoi) ---Leetcode
- leetcode 8. String to Integer (atoi)
- Leetcode: 8. String to Integer (atoi)(JAVA)
- 12.按键驱动程序设计(7)-阻塞型驱动设计
- Design Twitter
- DB2表被锁死,如何解锁
- Android开发——java.lang.IllegalStateException: The specified child already has a parent.
- 【LeetCode】 419. Battleships in a Board
- 【leetcode】8. String to Integer (atoi)
- Ajax_典型应用_验证用户名是否
- 网络程序设计课程总结
- Ajax_典型应用_购物车添加商品
- 微信公众号基础01_利用git免费在新浪云搭建测试号服务器
- LeetCode笔记:183. Customers Who Never Order
- Linux内核-内存-硬件高速缓存和TLB原理
- 字符集和字符编码
- Windows核心编程笔记(二) Widnwos下的字符处理