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.
</br>
Solution
atoi, which means alphanumeric to integer
, requires the function to input a string of numbers and convert it into an integer.
In order to do that, we first have to ignore all the blank spaces and start outputting integer once encountering the first non-blank characters. Also, the sign of the string should also be taken care of. Once we hit the decimal point or next blank space, the output will be terminated.
To achieve the requirement above, we have to consider all the possible inputs. Firstly, we should consider the empty string or a string of all blanks, either way we should return 0. Additionally, even if the string is valid, we should still return 0 when no valid conversion is available. Finally, when the output overflows, we should return the MAX_INT or MIN_INT.
To get specific digit at any given position, we can use charAt( ) function.
The code is shown as below.
Java
public class Solution {
public int myAtoi(String str) {
int index = 0, current = 0, sign = 1;
long output = 0;
//empty
if (str.length() == 0)
return 0;
while (index < str.length() && str.charAt(index) == ' ')
index ++;
//all blank spaces
if (index >= str.length())
return 0;
//sign
if (str.charAt(index) == '+' || str.charAt(index) == '-'){ //if there is no sign, then the output is positive.
sign = str.charAt(index) == '+' ? 1 : -1;
index += 1;
}
while (index < str.length()){
current = str.charAt(index) - '0';
if (current < 0 ||current > 9)
break;
output = output * 10 + current;
index ++;
if ((int)output != output)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
return (int)output*sign;
}
}
</br>