String to Integer (atoi) Cont…

Monisha Mathew
2 min readMar 12, 2019

--

Question: Implement atoi which converts a string to an integer. Find the detailed question here.

In case this is your first time fiddling with this question, I would highly recommend you to have a look at a simpler strategy mentioned here to begin with.

Approach 2: To start off from where we left off. The previous approach heavily depended on string being parsed into integer. If we tried converting an invalid string such as — an empty string, too long a sequence of numbers (positive or negative)— then an exception was thrown. We relied on this exception step to return the appropriate alternate value. This approach although acceptable, took too long to run.

Inspired by another post(you may check it out here), let’s try a different strategy, summarized below —

  • Use a bigger container to hold the (possible) overflow value
  • Ensure that the value in the container is within the allowed int range before returning (make sure you cast it to int)
  • If outside the range, return the appropriate alternate value

Quick peek at the code —

//Approach 2
//Runtime: 14ms
//Memory usage: 38.6MB
class Solution {
public int myAtoi(String str) {
char[] chars = str.trim().toCharArray();

if(chars.length==0){
return 0;
}
int sign = 1;
int start = 0;
if(chars[0]=='-'){
start++;
sign = -1;
} else if(chars[0]=='+'){
start++;
}
double finalInt = 0;
for(int i = start; i<chars.length; i++){
if(chars[i]>='0' && chars[i]<='9'){
finalInt=finalInt*10 + chars[i]-'0';
} else {
break;
}
}
finalInt*=sign;
if(finalInt>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
} else if(finalInt<Integer.MIN_VALUE){
return Integer.MIN_VALUE;
} else {
return (int)finalInt;
}
}
}

For a faster implementation you might want to check this out.

Find more posts here.

Cheers & Chao!

--

--