String to Integer (atoi)

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.

java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class Solution {
public static int myAtoi(String str) {
if(str==null||str.length()<1)
{
return 0;
}
//去两边的空白
str=str.trim();
//判断正负
int flag=1;
int i=0;
if(str.charAt(0)=='+')
{
i++;
}
if(str.charAt(0)=='-')
{
flag=-1;
i++;
}
//保存在double类型下,防止溢出
double result=0;
for(;i<str.length();i++)
{
if(str.charAt(i)>='0'&&str.charAt(i)<='9')
{
result=result*10+(str.charAt(i)-'0');
}
else
break;
}
if(flag==-1)
result*=-1;
//处理边界情况
if(result>Integer.MAX_VALUE)
result=Integer.MAX_VALUE;
if(result<Integer.MIN_VALUE)
result=Integer.MIN_VALUE;
return (int)result;

}
}