转换字符串到整数——LintCode
2015-12-14 14:56
423 查看
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
您在真实的面试中是否遇到过这个题?
Yes
样例
"10" =>10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
*************************************************
简直了……各种没想到的数据,代码很乱……水过去的
您在真实的面试中是否遇到过这个题?
Yes
样例
"10" =>10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
*************************************************
简直了……各种没想到的数据,代码很乱……水过去的
public class Solution { /** * @param str: A string * @return An integer */ public int atoi(String str) { // write your code here if(str == null) return 0; //合法 str = str.trim(); int num = 0,flag = 0; StringBuffer sb = new StringBuffer(); for(int i=0;i<str.length();i++) { char c = str.charAt(i); if(c >= '0' && c <= '9' || c == '.' || (c == '-' || c== '+')) { if(c >= '0' && c <= '9') flag = 1; if((c == '-' || c == '+') && i!=0) break; sb.append(c); } else if(flag == 1) { break; } if(c == '.') num++; } if(num > 1 ) return 0; str = sb.toString(); if(str.length() == 0 || (str.length() == 1 && (str.equals("+")||str.equals("-")))) return 0; if(num == 1) { String[] s = str.split("\\."); str = s[0]; } if(str.charAt(0) == '-') { if(str.length() < 11) return Integer.parseInt(str); if(str.length() > 11) return Integer.MIN_VALUE; String s = str.substring(1, str.length()-1); String s_ = str.substring(str.length()-1,str.length()); int x = Integer.parseInt(s); if(x > 214748364 || (x == 214748364 && Integer.parseInt(s_)>7)) return Integer.MIN_VALUE; x = Integer.parseInt(str); return x; } else{ if(str.length() < 10) return Integer.parseInt(str); if(str.length() > 10) return Integer.MAX_VALUE; String s = str.substring(0, str.length()-1); String s_ = str.substring(str.length()-1,str.length()); int x = Integer.parseInt(s); if(x > 214748364 || (x == 214748364 && Integer.parseInt(s_)>7)) return Integer.MAX_VALUE; x = Integer.parseInt(str); return x; } } }
相关文章推荐
- fir.im Weekly - 94 个 iOS 开发资源推荐
- Cef设置Cookie
- spring constructor-arg name UnsatisfiedDependencyException 本来打算发在stack overflow上的,死活发不出去,先记着吧
- 安卓学习之路3之插件TextView、EditText和ImageView
- Android入门1:使用VideoView和MediController播放视频
- 微信支付APP支付完全攻略
- JavaNote
- 源码推荐(12.14B):无限图片轮播器,加载时日食效果
- 吐槽在讲课以后
- 迭代器(Iterator)
- (ZZ) 设计模式:观察者模式
- java.lang.IllegalArgumentException: Page directive: invalid value for import
- MEF
- 几道和三角函数有关的题目
- pg_dump和pg_restore
- Android sdk镜像设置
- Scala编程实例:使用Set和Map
- WebService:CXF开发
- Java类文件结构
- 老男孩教育实践:参观森华易腾的IDC机房