題目:實(shí)現(xiàn)一個(gè)函數(shù)stringToInt,實(shí)現(xiàn)把字符串轉(zhuǎn)換成整數(shù)這個(gè)功能鼎天,不能使用atoi或者其他類似的庫(kù)函數(shù)。
代碼如下:
package demo;
/**
* 把字符串轉(zhuǎn)換成整數(shù)
*
* @author xiangdonglee
*
*/
public class Test49 {
public static int stringToInt(String num) {
if (num == null || num.length() < 1) {
throw new NumberFormatException(num);
}
char first = num.charAt(0);
if (first == '-') {
return parseString(num, 1, false);
} else if (first == '+') {
return parseString(num, 1, true);
} else if (first <= '9' && first >= '0') {
return parseString(num, 0, true);
} else {
throw new NumberFormatException(num);
}
}
/**
* 對(duì)字符串進(jìn)行解析
*
* @param num
* 數(shù)字串
* @param index
* 開(kāi)始解析的索引
* @param positive
* 是正數(shù)還是負(fù)數(shù)
* @return 返回結(jié)果
*/
private static int parseString(String num, int index, boolean positive) {
if (index >= num.length()) {
throw new NumberFormatException(num);
}
int result;
long tmp = 0;
while (index < num.length() && isDigit(num.charAt(index))) {
tmp = tmp * 10 + num.charAt(index) - '0';
// 保證求得的值不超過(guò)整數(shù)的最大絕對(duì)值
if (tmp > 0x8000_0000L) {
throw new NumberFormatException(num);
}
index++;
}
if (positive) {
if (tmp >= 0x8000_0000L) {
throw new NumberFormatException(num);
} else {
result = (int) tmp;
}
} else {
if (tmp == 0x8000_0000L) {
result = 0x8000_0000;
} else {
result = (int) -tmp;
}
}
return result;
}
/**
* 判斷字符是否是數(shù)字
*
* @param c
* 字符
* @return true:是暑竟;false:否
*/
private static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
public static void main(String[] args) {
System.out.println(Integer.parseInt(Integer.MIN_VALUE + ""));
System.out.println(0x8000_0000L);
// System.out.println(stringToInt(""));
System.out.println(stringToInt("123"));
System.out.println(stringToInt("+123"));
System.out.println(stringToInt("-123"));
System.out.println(stringToInt("1a123"));
System.out.println(stringToInt("+2147483647"));
System.out.println(stringToInt("-2147483647"));
// System.out.println(stringToInt("+2147483648"));
// System.out.println(stringToInt("-2147483648"));
// System.out.println(stringToInt("+"));
// System.out.println(stringToInt("-"));
}
}
來(lái)源:http://blog.csdn.net/derrantcm/article/details/46811799