8. String to Integer (atoi)
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.
思路:四种情况一步一步来,最美的是int digit=s.charAt(i)-'0'
public class Solution {
public int myAtoi(String str) {
int index=0, sign=1, result=0;
//1. Empty string
if(str.length()==0) return 0;
//2. Remove space
while(str.charAt(index)==' '&&index<str.length())
index++;
//3. sign
if(str.charAt(index)=='+'||str.charAt(index)=='-'){
sign = str.charAt(index)=='+'? 1:-1;
index++;
}
if (index==str.length())
return 0;
if(str.charAt(index)=='+'||str.charAt(index)=='-')
return 0;
//4. convert number
while(index<str.length()){
int digit = str.charAt(index)-'0';
if(digit < 0 || digit > 9) break;
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;
}
int newResult = result*10+digit;
result = newResult;
index++;
}
return result*sign;
}
}