LeetCode 8. String to Integer (atoi)
来源:互联网 发布:windows系统快捷键设置 编辑:程序博客网 时间:2024/06/15 23: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.
这个题真的是很难考虑到那么多种奇葩的情况,靠debug来刷新三观。
public class Solution { public int myAtoi(String str) { if (str.length()==0||str==null){ return 0; } for(int i=0;i<str.length();i++){ if(str.charAt(i)==' '){ continue; } str = str.substring(i); break; } int flag = 1; if(str.charAt(0)=='+'){ flag = 1; str = str.substring(1); } else if(str.charAt(0)=='-'){ flag = -1; str = str.substring(1); } long ans = 0; int len = str.length(); for(int i=0;i<len;i++){ if(str.charAt(i)>='0'&&str.charAt(i)<='9'){ ans = ans*10+Character.getNumericValue(str.charAt(i)); if(flag*ans>Integer.MAX_VALUE){ return Integer.MAX_VALUE; } if(flag*ans<Integer.MIN_VALUE){ return Integer.MIN_VALUE; } } if((str.charAt(i)<'0'||str.charAt(i)>'9')){ break; } } return (int)ans*flag; }}注意考虑空格、正负号、溢出等等情况
0 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)
- poj 1442 splay 模板题
- Java_hashCode简介
- jQuery绑定事件的四种方式
- Predix之玩转树莓派(2) 从传感器采集数据
- HDOJ-1016Prime Ring Problem(DFS)
- LeetCode 8. String to Integer (atoi)
- Leetcode 80]Remove Duplicates from Sorted Array II
- 产品经理之web端产品设计-全栈工程师熊盼
- 课堂笔记_ 材质反射属性模型BRDF_01
- git的使用(一)
- Flatten Binary Tree to Linked List
- Linux命令缩写
- 仿腾讯云单选控件
- codeforces Minimum number of steps 思维