最開始用int處理,發現通過率只有76%。檢查發現對於Integer.MAX_VALUE/MIN_VALUE越界無法處理。於是有了利用BigInteger來處理越界問題。
題目:
將一個字符串轉換成一個整數,要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0
代碼實現:(運行時間34ms)
import java.math.BigInteger;
public class Solution {
public static int StrToInt(String str) {
BigInteger big = StrToInteger(str);
if (big.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0
|| big.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
return 0;
}
return Integer.valueOf(big.toString());
}
private static BigInteger StrToInteger(String str) {
String regex = "^[-+][0-9]*|[0-9]*$";
if (!str.matches(regex) || str.length() == 0 || str == null) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.ZERO;
// 符號位
boolean isNegative = (str.charAt(0) == '-');
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// 判斷符號爲可能爲 + -
if (i == 0 && (ch == '+' || ch == '-')) {
continue;
}
result = result.multiply(BigInteger.TEN).add(BigInteger.valueOf((ch - '0')));
}
return isNegative? result.negate() : result;
}
}