8. String to Integer (atoi)
class Solution {
public int myAtoi(String s) {
int sign =1;
int index=0;
//ignore lead whitesapce
while(index<s.length() && s.charAt(index)==' '){
index++;
}
// check sign
if(index<s.length() && s.charAt(index)=='+'){
index++;
}else if (index<s.length() && s.charAt(index) == '-'){
index++;
sign = -1;
}
int result = 0;
// move pointer until it reaches the firt non-digit char
while(index<s.length() && s.charAt(index)>='0' && s.charAt(index)<='9'){
int digit = s.charAt(index)-'0';
// Key: if reuslt is just equal to MIN_VALUE will be return from here,
// if result is just equal to MAX_VALUE, will be return outside the while loop
if (Integer.MAX_VALUE/10<result ||
(Integer.MAX_VALUE/10==result && Integer.MAX_VALUE%10<digit)){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result=result*10+digit;
index++;
}
return sign*result;
}
}
Last updated
Was this helpful?