Created
February 16, 2020 02:05
-
-
Save wushbin/b0932d238fef69c7c57b70779303c895 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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