My code can account for leading whitespace and non-digit characters. It fails the fourth and fifth cases. Input: s = "words and 987" and Input: s = "-91283472332" cases. I"m not sure how to account for these cases.
class Solution {
public int myAtoi(String s) {
int length = s.length();
boolean pos = true;
int i = 0, num = 0;
if(s.length() == 0) {
return 0;
}
while(s.charAt(i) == ' ') {
i++;
}
if(s.charAt(i) == '-') {
pos = false;
i++;
}
else if(s.charAt(i) == '+') {
pos = true;
i++;
}
while(i < length) {
if(Character.isDigit(s.charAt(i))) {
num = (num * 10) + Character.getNumericValue(s.charAt(i));
}
i++;
}
if(!pos) {
num *= -1;
}
if(num < Integer.MIN_VALUE) {
num = Integer.MIN_VALUE;
}
else if(num > Integer.MAX_VALUE) {
num = Integer.MAX_VALUE;
}
return num;
}
}
public static int myAtoi(String str) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (buf.length() == 0) {
if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9'))
buf.append(ch);
else if (ch != ' ')
return 0;
} else if (ch < '0' || ch > '9')
break;
else
buf.append(ch);
}
try {
BigDecimal res = new BigDecimal(buf.toString());
if (res.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0)
return Integer.MAX_VALUE;
if (res.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0)
return Integer.MIN_VALUE;
return res.intValue();
} catch(Exception e) {
return 0;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.