Skip to content

Instantly share code, notes, and snippets.

@wushbin
Created February 16, 2020 02:05
Show Gist options
  • Save wushbin/b0932d238fef69c7c57b70779303c895 to your computer and use it in GitHub Desktop.
Save wushbin/b0932d238fef69c7c57b70779303c895 to your computer and use it in GitHub Desktop.
class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
int ptr = 0;
int len = str.length();
while(ptr < len && str.charAt(ptr) == ' ') {
ptr++;
}
int sign = 1;
if (ptr < len && !Character.isDigit(str.charAt(ptr))) {
if (str.charAt(ptr) == '+') {
sign = 1;
} else if (str.charAt(ptr) == '-') {
sign = -1;
} else {
return 0;
}
ptr++;
}
int res = 0;
while(ptr < len) {
char c = str.charAt(ptr);
if (c < '0' || c > '9') {
break;
}
int num = c - '0';
if (Integer.MAX_VALUE / 10 < res || (Integer.MAX_VALUE - res * 10 ) < num) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + num;
ptr++;
}
return sign * res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment