Implement atoi to convert a string to an integer.
Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Title: Implementing String to Integer
Considerations: Consider all possible inputs (pits);
public class Solution {
public int myatoi (String str) {
}
}
Problem-solving experience: The topic itself is not particularly difficult, as long as a benchmark is found, Java is ' 0 ' (char) according to each character in the input string, and the difference between the datum, determine the multiplication to multiply, Judge +,-, the idea is very simple, the difficulty lies in:
1. Various extreme boundary parameters, Leetcode test has 1047 cases, most of the failure is estimated in the "-+12", "-", "+", "12a34" such as corner cases on ;
2.int integer upper and lower boundary processing;
For the boundary, I here directly with a double to expand and then to int, temporarily can not think of AH good processing method, the following code:
public int myatoi (String str) {
if (str = = NULL | | str.length () = = 0) {
return 0;
}
Boolean Flag_neg = false;
str = Str.trim ();
int len = Str.length ()-1;
Double digit = 1, count = 0,res = 0;
Char std = ' 0 ';
while (len >= 0) {
char C = Str.charat (len);
if ('-' = = = c) {
Flag_neg = true;
count++;
} else if (c = = ' + ') {
Flag_neg = false;
count++;
} else if (c >= ' 0 ' && C <= ' 9 ') {
int con = Str.charat (len)-STD;
Res + = con * digit;
Digit *= 10;
} else {
res = 0;
digit = 1;
}
len--;
}
res = Flag_neg? -res:res;
if (res >= integer.max_value) {
res = Integer.max_value;
} else if (res <= integer.min_value) {
res = Integer.min_value;
}
if (Count > 1) return 0;
return (int) res;
}
Leetcode-string to Integer (atoi) strings to integers