- 最吐血的一道题了.调了好久才通过.大无语,脑袋都晕了💫😵💫
- 感觉也没有什么特别的高深的算法技巧吧,就是不断调试不断调试.
- 下午睡了一觉,起来被这题折腾累了,今天就到这了.😵💫😵💫😵💫😵💫😵💫
class Solution {
public int myAtoi(String s) {
if(s == null || s.equals("")) {
return 0;
}
s = removeHeadZero(s.trim());
if(s == null || s.equals("")) {
return 0;
}
char[] str = s.toCharArray();
if(!isValid(str)) {
return 0;
}
boolean posi = str[0] == '-' ? false : true;
int minq = Integer.MIN_VALUE / 10;
int minr = Integer.MIN_VALUE % 10;
int res = 0;
int cur = 0;
for(int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; i < str.length; i++) {
cur = '0' - str[i];
if((res < minq) || (res == minq && cur < minr)) {
return posi ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + cur;
}
if(posi && res == Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
}
return posi ? -res : res;
}
public static String removeHeadZero(String str) {
boolean r = (str.startsWith("+") || str.startsWith("-"));
int s = r ? 1 : 0;
for(;s < str.length();s++) {
if(str.charAt(s) != '0') {
break;
}
}
int e = -1;
for(int i = str.length() - 1; i >= (r ? 1 : 0); i--) {
if(str.charAt(i) < '0' || str.charAt(i) > '9') {
e = i;
}
}
return (r ? String.valueOf(str.charAt(0)) : "") + str.substring(s,e == -1 ? str.length() : e);
}
public static boolean isValid(char[] chas){
if(chas[0] != '-' && chas[0] != '+' && (chas[0] < '0' || chas[0] > '9')){
return false;
}
if((chas[0] == '-' || chas[0] == '+') && chas.length == 1) {
return false;
}
for(int i = 1; i < chas.length;i++) {
if(chas[i] < '0' || chas[i] > '9') {
return false;
}
}
return true;
}
}