有一个小问题,首先用if(str == null) return 0;来判断特殊输入,这样是不行的。
后来用if(str.length() == 0)来判断,也是不行的。
因为可以有一个空字符,后面会越界。
正确的方法是在str.trim().toCharArray()后判断字符数组c的长度。
*还有就是判断越界可以用除10的结果与上次结果比较,很巧妙。
class Solution { public int strToInt(String str) { //if(str.length() == 0) return 0; char[] c = str.trim().toCharArray(); if(c.length == 0) return 0; int sign = 1, i = 1; int res = 0,tmp = 0; //判断正负号 if(c[0] == ‘-‘) sign = -1; else if(c[0] != ‘+‘) i = 0; for(int j = i; j < c.length; j++){ if(c[j] >‘9‘ || c[j] < ‘0‘) break; tmp = res; res = res * 10 + (c[j] - ‘0‘); //如果除10的结果和上一次的计算结果不同,意味发生越界。 if(tmp != (res /10)) return sign == 1 ? Integer.MAX_VALUE :Integer.MIN_VALUE; } //最简单写成 return res*sign; if(sign == -1) res = -res; return res; } }
原文:https://www.cnblogs.com/deerlet/p/14594381.html