??
Introduction
??
Stoi is a very common problem,Leetcode Also, string conversion to a number generally has a ready-made function to implement such a function, but sometimes we need to understand the specific implementation, because although it is a very common problem, But there are a lot of issues to consider, especially the corner case, which typically takes two points into account: one is the symbol, the other is out of bounds.
??
Analyze problems
??
If there are spaces in front of the string, generally there is no space in the middle, but there may be spaces before and after, so we first need to remove the extra space characters, using the trim function
??
Then it is possible that the first position of the string is signed, such as the negative sign, for positive numbers, there may be, there may not be, how to solve this problem, in fact, if there is a symbol is definitely at the first character, so we just have to determine the first character is not a minus, if it is, We need to sign the logo, if it is not a minus sign, but a plus, then skip directly, if there is no symbol, then read from the first number
??
In addition, it is possible that the preceding strings are obediently is the number, the middle of an unusual character, then we need to do this time to divide the situation, the first we can keep the previous number, discard the exception character behind the thing, the second is we directly simple rude return error
??
There is a string representation of the number may be large, it is possible to cross the border, then we should do, can output, out of bounds, can also return the nearest integer
??
Also use a boolean value to indicate whether the normal completion, and for some exception handling, can vary from individual to requirements, depending on the
??
Solve the problem
??
Static Boolean finished = false;
public int atoi (String str) {
str=str.trim ();
int i = 0;
Boolean minus = false;
if (Str.charat (0) = = '-') {
minus = true;
i++;
} else if (Str.charat (0) = = ' + ') {
i++;
}
Long min_value = Integer.min_value;
Long max_value = Integer.max_value;
Long num = 0;
??
for (; i < length &&!finished; i++) {
char C = Str.charat (i);
if (c >= ' 0 ' && C <= ' 9 ') {
Num *= 10;
num + = c-' 0 ';
} else {
num=0;
Break
}
??
if (minus && 0-num < Min_value) {
return integer.min_value;
}
if (!minus && num > Max_value) {
return integer.max_value;
}
}
if (i==length) {
Finished = true;
}
return minus? New Long (0-num). Intvalue (): New Long (num). Intvalue ();
}
Sword Point offer Solution Report (Java Edition)--string converted to number 49