问题链接
String to Integer (atoi) | LeetCode OJ
问题描述
写一个方法,将字符串转换为32位有符号的整数。
解决办法
public class Solution {
public int myAtoi(String str) {
//if str is empty,return 0
if (str.length() == 0) {
return 0;
}
//remove empty space
while (str.length() > 0 && str.charAt(0) == ' ') {
str = str.substring(1);
}
while (str.length() > 0 && str.charAt(str.length() - 1) == ' ') {
str = str.substring(0, str.length() - 1);
}
//if str is empty,return 0
if (str.length() == 0) {
return 0;
}
//remove plus-minus sign
boolean isNegative = false;
if (str.indexOf("-") == 0) {
isNegative = true;
str = str.substring(1);
} else if (str.indexOf("+") == 0) {
str = str.substring(1);
}
//remove zero
while (str.length() > 0 && str.charAt(0) == '0') {
str = str.substring(1);
}
if (str.length() == 0) {
return 0;
}
int result = 0;
int multiplier = 1;
int position = 0;
int[] legitIntArray = new int[str.length()];
int legitPosition = 0;
boolean stop = false;
while (!stop) {
char c = str.charAt(position);
try {
int charNumber = charToInt(c);
legitIntArray[position] = charNumber;
position++;
if (position >= str.length()) {
legitPosition = position - 1;
stop = true;
}
} catch (NumberFormatException e) {
legitPosition = position - 1;
stop = true;
}
}
if (legitPosition > 9) {
if (isNegative) {
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
for (int i = legitPosition; i >= 0; i--) {
try {
int charNumber = legitIntArray[i];
int charNumberWithMultiplier = safeMultiply(charNumber, multiplier);
result = safeAdd(result, charNumberWithMultiplier);
multiplier *= 10;
} catch (ArithmeticException e) {
if (isNegative) {
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
}
if (isNegative) {
return -result;
}
return result;
}
/**
* @see https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow
* @throws ArithmeticException
*/
static final int safeAdd(int left, int right) throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
**
* @see https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow
* @throws ArithmeticException
*/
static final int safeMultiply(int left, int right) throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE / right
|| left < Integer.MIN_VALUE / right
: (right < -1 ? left > Integer.MIN_VALUE / right
|| left < Integer.MAX_VALUE / right
: right == -1
&& left == Integer.MIN_VALUE)) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
public static int charToInt(char c) throws NumberFormatException {
switch (c) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
}
throw new NumberFormatException("Illegal char " + String.valueOf(c));
}
}