您的位置:首页 > 其它

转换字符串到整数——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

*************************************************
简直了……各种没想到的数据,代码很乱……水过去的
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: