# [LeetCode]8. String to Integer (atoi)

Easy

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.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

public class Solution {
public int myAtoi(String str) {
long sum = 0;
if(!str.equals("")){
char[] mm = str.toCharArray();
int[] ii = new int[mm.length+1];
boolean begin = false;
int b = 0;
for(int a=0;a<mm.length;a++){
if(mm[a]==' '&&!begin)
continue;
if(!begin&&(mm[a]=='+'||mm[a]=='-'||(mm[a]>='0'&&mm[a]<='9'))){
ii[0] = mm[a]=='-'?-1:1;
if(a<mm.length-1&&(mm[a]=='-'||mm[a]=='+'))
a++;
begin = true;
}

if(mm[a]>='0'&&mm[a]<='9'){
ii[++b] = mm[a]-'0';
}else{
break;
}
}
for(int x=0;b>0;b--){
sum += ii[b]*(Math.pow(10, x));
x++;
}
sum *= ii[0];
if(sum>2147483647)
sum = Integer.MAX_VALUE;
if(sum<-2147483648)
sum = Integer.MIN_VALUE;
}
return (int)sum;
}
}

4ms:

            if (str == null || str.length() < 1)
return 0;

// trim white spaces
str = str.trim();

char flag = '+';

// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;

// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}

if (flag == '-')
result = -result;

// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;

return (int) result;
• 本文已收录于以下专栏：

举报原因： 您举报文章：[LeetCode]8. String to Integer (atoi) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)