代码如下:
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
public class Solution { | |
public int atoi(String str) { | |
if(str == null) | |
return 0; | |
int len = str.length(); | |
if (len == 0) | |
return 0; | |
int start = 0; | |
boolean isNeg = false; | |
while (start < len && str.charAt(start) == ' ') | |
start++; | |
if (start == len) | |
return 0; | |
if (str.charAt(start) == '+') | |
start++; | |
else if (str.charAt(start) == '-') { | |
isNeg = true; | |
start++; | |
} | |
if (start == len) | |
return 0; | |
int res = 0; | |
for (int i = start; i < len; i++) { | |
if (!isNum(str.charAt(i))) | |
return res; | |
int add = str.charAt(i) - '0'; | |
if (isOverflow(isNeg, res, add)) | |
return isNeg? Integer.MIN_VALUE: Integer.MAX_VALUE; | |
else | |
res = isNeg? 10 * res - add: 10 * res + add; | |
} | |
return res; | |
} | |
private boolean isOverflow(boolean isNeg, int base, int add) { | |
if (!isNeg) { | |
int upperBound = (Integer.MAX_VALUE - add) / 10; | |
return upperBound < base; | |
} else { | |
int lowerBound = (Integer.MIN_VALUE + add) / 10; | |
return lowerBound > base; | |
} | |
} | |
private boolean isNum(char c) { | |
int digit = c - '0'; | |
return digit <= 9 && digit >= 0; | |
} | |
} |
No comments:
Post a Comment