[LintCode] String to Integer(atoi)
public int atoi(String str) { // write your code here if(str == null || str.length() == 0) return 0; str = str.trim(); int i = 0; char sign = '+'; if(str.charAt(0) == '+') i++; else if(str.charAt(0) == '-'){ i++; sign = '-'; } int res = 0; while(i < str.length() && str.charAt(i) >='0' && str.charAt(i)<='9') { if(Integer.MAX_VALUE / 10 < res || (Integer.MAX_VALUE / 10 == res &&Integer.MAX_VALUE%10 < (str.charAt(i) - '0'))) return sign == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE; res = res * 10 + (str.charAt(i) - '0'); i++; } return sign == '-'? -res : res; }
Leave A Comment