2014
11-18

# LeetCode-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.

spoilers alert… click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

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.

\begin{enumerate}
\item 不规则输入，但是有效，"-3924x8fc"， " + 413",
\item 无效格式，" ++c", " ++1"
\item 溢出数据，"2147483648"
\end{enumerate}

// LeetCode, String to Integer (atoi)
// 时间复杂度O(n)，空间复杂度O(1)
class Solution {
public:
int atoi(const char *str) {
int num = 0;
int sign = 1;
const int n = strlen(str);
int i = 0;

while (str[i] == ' ' && i < n) i++;

if (str[i] == '+') {
i++;
} else if (str[i] == '-') {
sign = -1;
i++;
}

for (; i < n; i++) {
if (str[i] < '0' || str[i] > '9')
break;
if (num > INT_MAX / 10 ||
(num == INT_MAX / 10 &&
(str[i] - '0') > INT_MAX % 10)) {
return sign == -1 ? INT_MIN : INT_MAX;
}
num = num * 10 + str[i] - '0';
}
return num * sign;
}
};


Java代码:

public class Solution {
public int atoi(String str) {
if(str == null || str.length()==0) return 0;
int res = 0, i= 0;
while (str.charAt(i) == ' ') i++;
int sign = str.charAt(i) == '-' ? -1:1;
if(str.charAt(i) == '-' || str.charAt(i) == '+') i++;
char tmp;
while (i<str.length() && ((tmp = str.charAt(i)) >= '0' && tmp <= '9') ){
if(res > 214748364 || (res == 214748364) && tmp > '7')
return sign == 1 ? 2147483647:-2147483648;
res = 10 * res + tmp - '0';
i++;
}
return res * sign;
}
}

1. Good task for the group. Hold it up for every yeara??s winner. This is a excellent oppotunity for a lot more enhancement. Indeed, obtaining far better and much better is constantly the crucial. Just like my pal suggests on the truth about ab muscles, he just keeps obtaining much better.