class Solution {
public int myAtoi(String str) {
str = str.trim();
if("".equals(str))return 0;
if (!"+-0123456789".contains(str.charAt(0) + "")) return 0;
if(str.length()==1 && (str.charAt(0) == '-' || str.charAt(0) == '+' )) return 0;
int mma = -1;
StringBuffer result = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if(mma == -1){
if("+-0123456789".contains(str.charAt(i) + "")){
if (str.charAt(i) != '0') {
result.append(str.charAt(i));
}
mma = 1;
if(str.charAt(i) != '+'&&str.charAt(i) != '-' && str.charAt(i) != '0'){
mma = 2;
}
continue;
}else{
break;
}
}if(mma == 1){
if("0123456789".contains(str.charAt(i) + "")){
if (str.charAt(i) != '0') {
result.append(str.charAt(i));
mma = 2;
}
continue;
}else{
break;
}
}if(mma == 2){
if("0123456789".contains(str.charAt(i) + "")){
result.append(str.charAt(i));
continue;
}else{
break;
}
}
}
int resultNum = 0;
String result1 = result.toString() ;
if (result1.length() > 0) {
if (result1.charAt(0) == '+') {
result1 = result1.replace("+", "");
}
}
if (result1.length() > 0) {
String signStrUp = Integer.MAX_VALUE + "";
String signStrDown = Integer.MIN_VALUE + "";
int p = result1.length();
if (result1.charAt(0) == '-') {
if (p > signStrDown.length()) {
return Integer.MIN_VALUE;
} else if (p == signStrDown.length()) {
if (!compare(result1, signStrDown, 0)) {
return Integer.MIN_VALUE;
}
;
}
} else {
if (p > signStrUp.length()) {
return Integer.MAX_VALUE;
} else if (p == signStrUp.length()) {
if (!compare(result1, signStrUp, 0)) {
return Integer.MAX_VALUE;
}
;
}
}
if ("+".equals(result1) || "-".equals(result1)) {
return 0;
}
resultNum = Integer.parseInt(result1);
}
return resultNum;
}
private static boolean compare(String c, String z, int i) {
if (i == z.length()) {
return true;
}
if (c.charAt(i) > z.charAt(i)) {
return false;
} else if (c.charAt(i) == z.charAt(i)) {
int m = i + 1;
return compare(c, z, m);
}
return true;
}
}
字符串转换整数 (atoi)
最新推荐文章于 2023-02-12 10:49:39 发布