PROBLEM STATEMENT
This question is from Leetcode – String to Integer (atoi). The problem statement in short is given below:
Implement a function that converts a string to a 32-bit signed integer.
SOLUTION
public int myAtoi(String s) {
int strToInt = 0;
s = s.strip();
int len = s.length();
StringBuilder str = new StringBuilder();
boolean isNeg = false;
for(int i=0; i<len; i++) {
Character c = s.charAt(i);
if(i == 0 && (c == '-' || c == '+') ) {
// if '-' is the first char then turn the flag to true
if(c == '-')
isNeg = true;
continue;
}
// if char is digit then append to string
if(Character.isDigit(c) ) {
str = str.append( Character.toString(c) );
continue;
}
// if char is not a digit then break
if(!Character.isDigit(c) ) {
break;
}
} // endfor
// convert string to integer
if(!str.isEmpty()) {
try {
strToInt = Integer.valueOf(str.toString());
}
// if val is too large for int then return the min / max int val
catch(NumberFormatException nfe) {
if(isNeg)
return Integer.MIN_VALUE;
else
return Integer.MAX_VALUE;
}
}
// if flag is true then multiply by -1
if(isNeg) {
strToInt = strToInt * -1;
}
return strToInt;
}
You can check out the code from Github here: String to Integer (atoi) – First Approach
PERFORMANCE ANALYSIS
RUNTIME | 4 ms | Beats 8.58 % |
MEMORY | 42.84 MB | Beats 15.56 % |
TIME COMPLEXITY | O (N) |