#问题描述
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.
##问题分析
该问题意思很明白就是要将字符串转换为数字
其中关键点是对特殊的情况进行讨论
- 输入为“”、“ ”的时候应该返回0
- 输入为“++123”的时候应该为0
- 输入为“123”返回123,输入为“-123”返回为-123
- 输入字符串大于“2147483647”或者小于“-2147483648”时应该将INT_MAX或者INT_MIN返回
- 还有其中如果存在非数字的时候,返回0
##JAVA代码
//3 key things you need to know:
//1. first non-whitespace character must be sign or digit
//2. two consecutive signs is invalid format (“++82” invalid)
//3. only whitespaces and digits are allowed after the sign ( “- 082jk s” valid)
public class Solution {
public static int atoi(String str) {
if(str.length() == 0) {
return 0;
}
int num = 0;
int index = 0;
int sign = 1;
int signCount = 0;
//skip all leading whitespaces
while(str.charAt(index) == ‘ ‘ && index < str.length()) {
index++;
}
if(str.charAt(index) == ‘+’) {
signCount++;
index++;
}
if(str.charAt(index) == ‘-‘) {
signCount++;
sign = -1;
index++;
}
//two consecutive signs is invalid
if(signCount >= 2) {
return 0;
}
while(index < str.length()) {
char ch = str.charAt(index);
if(ch < ‘0’ || ch > ‘9’) break;
//输入字符串太大情况
if(Integer.MAX_VALUE/10 < num || Integer.MAX_VALUE/10 == num && Integer.MAX_VALUE%10 < (ch - ‘0’)) {
return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
num = num 10 + (ch - ‘0’);
index++;
}
return sign num;
}
}