Implement atoi to convert a string to an integer.
Hint: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.
Analysis
The following cases should is considered for this problem:
1. Null or empty string2. White Spaces3. +/-Sign4. Calculate real value5. Handle min & Max
Java Solution
Public int atoi (String str) {
if Null | | Str.length () < 1)
return 0;
Trim White spaces
Char
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 * + (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;
}
Algorithm String to Integer (atoi)