leetCode 8. String to Integer (atoi) (字符串转整形) 解题思路和方法
来源:互联网 发布:iphone6手机壳淘宝 编辑:程序博客网 时间:2024/06/05 05:01
问题:
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.
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
思路:此题不算难,但是最无可忍受的是出题方没有把规则告诉我们,所以这题怎么理解规则成了关键,我只能在不断试错中一步步走出正确的代码。
ps:这题通过率不高完全是出题方的恶意。
代码如下:
public int myAtoi(String str) { int max = Integer.MAX_VALUE; int min = Integer.MIN_VALUE; //首位数字是否出现 boolean isFirstNum = false; String s = ""; for(int i = 0; i < str.length();i++){ //只有数字前面的字符为空才接受,否则直接跳出循环返回0 if((str.charAt(i) >= '0' && str.charAt(i) <= '9') || str.charAt(i) == '+' || str.charAt(i) == '-'){ isFirstNum = true;//标记出现 s += str.charAt(i);//保存字符 }else{ if(str.charAt(i) != ' '){ break;//如果字符不为数字,也非空,直接结束 }else{ //如果为空,但是已经出现了数字,也结束 if(isFirstNum) break; } } } if(s.length() > 0){ if(s.length() == 1 && (s.charAt(0) == '+' || s.charAt(0) == '-') ){ //长度只有1且为符号的返回0 }else{ long x = 0; try{ //如果s长度超过14,则肯定超出int范围,分情况返回max或min if(s.length() > 14){ if(s.charAt(0) == '-'){ return min; }else{ return max; } } //转成long,大于max的取max,小于min的取min x = Long.parseLong(s); x = x > max? max:x; x = x < min ? min:x; return (int) x; } catch(Exception e){ //转型出错返回0 } } } return 0; }
0 0
- leetCode 8. String to Integer (atoi) (字符串转整形) 解题思路和方法
- leetCode 13.Roman to Integer (罗马数字转整形) 解题思路和方法
- 【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】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) 解题报告
- String to Integer (atoi) LeetCode 解题报告
- [leetcode] 8. String to Integer (atoi) 解题报告
- [Leetcode] 8. String to Integer (atoi) 解题报告
- leetcode解题报告8. String to Integer (atoi)
- 【LeetCode】- String to Integer (字符串转成整形)
- 1149 - Bin Packing(贪心)
- wget命令
- 函数式宏定义与普通函数的区别
- Unity 按照设定路线行走
- WIN8+VS2013+DirectX 3D (一)环境搭建
- leetCode 8. String to Integer (atoi) (字符串转整形) 解题思路和方法
- 键盘事件的调用顺序及获取键盘大小
- Linux内核很吊之 module_init解析 (下)
- 关于分支管理的问题
- 马斯克超等高铁或起首在亚洲建成
- 判定一个点是否在三角形内
- hdu 5276 YJCtricks time
- ecshop 调试分类页面技巧 debug_print_backtrace
- java 反射详解