8. String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/discuss/4672/JAVA-Easy-Version-To-Understand!!!!!!!!!!
用sum = sum*10 + 这位数字来计算
不能直接通过-Integer.MIN_VALUE来取负
1 class Solution { 2 public int myAtoi(String str) { 3 str = str.trim(); 4 if(str.length() == 0) return 0; 5 long sum = 0; 6 int sign = 1, start = 0; 7 if(str.charAt(0) == '-'){ 8 sign = -1; 9 start++; 10 }else if(str.charAt(0) == '+'){ 11 start++; 12 } 13 for(int i = start; i < str.length(); i++){ 14 if(Character.isDigit(str.charAt(i))){ 15 sum = sum*10 + (str.charAt(i) - '0'); 16 if(sign == 1 && sum > Integer.MAX_VALUE){ 17 return Integer.MAX_VALUE; 18 }else if(sign == -1 && sum*sign < Integer.MIN_VALUE){ 19 return Integer.MIN_VALUE; 20 } 21 }else{ 22 break; 23 } 24 } 25 return (int)sum * sign; 26 27 } 28 }
1 class Solution { 2 public int myAtoi(String str) { 3 str = str.trim(); 4 if(str.length() == 0) return 0; 5 long res = 0; 6 StringBuilder sb = new StringBuilder(); 7 if(str.charAt(0) == '+' || str.charAt(0) == '-' || (((str.charAt(0) - '0') >= 0) &&((str.charAt(0) - '0') <= 9))){ 8 if(((str.charAt(0) - '0') > 0) &&((str.charAt(0) - '0') <= 9)){ 9 sb.append(str.charAt(0)); 10 } 11 for(int i = 1; i < str.length(); i++){ 12 if(((str.charAt(i) - '0') >= 0) &&((str.charAt(i) - '0') <= 9)){ 13 if(str.charAt(i) == '0' && sb.length() == 0){ //开头是0不加入 14 continue; 15 } 16 sb.append(str.charAt(i)); 17 }else{ 18 break; 19 } 20 21 } 22 if(sb.length() == 0) return 0; //没有得到数字 23 if(sb.length() > 10){ //超过10位就是超过int的边界 直接可以return 24 if(str.charAt(0) == '-'){ 25 return Integer.MIN_VALUE; 26 }else{ 27 return Integer.MAX_VALUE; 28 } 29 } 30 res = Long.parseLong(sb.toString()); 31 if(str.charAt(0) == '-'){ 32 res = -res; 33 return (res < Integer.MIN_VALUE) ? Integer.MIN_VALUE : (int)res; 34 35 } 36 return (res > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)res; 37 38 39 }else{ 40 return (int)res; 41 } 42 43 } 44 }