题目描述:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
输入:
输入可能包含多个测试样例。
对于每个测试案例,输入为一个合法或者非法的字符串,代表一个整数n(1<= n<=10000000)。
输出:
对应每个测试案例,
若输入为一个合法的字符串(即代表一个整数),则输出这个整数。
若输入为一个非法的字符串,则输出“My God”。
陷阱:
* ①:对第一个符号为正负的判断;有符号,或者没有符号
* ②:对字符串中非法输入的判断,当字符串非法的时候,则输出“My God”
* ③:对于溢出情况下的判断,所以这个时候必要要使用BigInteger类来进行运算
package test1058;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String string = scanner.next();
BigInteger bigInteger = StringToInt(string);
if (bigInteger == null) {
System.out.println("My God");
} else {
System.out.println(bigInteger);
}
}
}
/**
* ①:对第一个符号为正负的判断;有符号,或者没有符号 ②:对字符串中非法输入的判断,当字符串非法的时候,则输出“My God”
* ③:对于溢出情况下的判断,所以这个时候必要要使用BigInteger类来进行运算
*
* @param str
* @return
*/
public static BigInteger StringToInt(String str) {
boolean flag = true;
if (str.length() == 0) {
return null;
}
char[] c = str.toCharArray();
int index = 0;
BigInteger result = BigInteger.valueOf(0);
if (c[index] == '+') {
index++;
} else if (c[index] == '-') {
index++;
flag = false;
}
while (index < str.length()) {
if (c[index] < '0' || c[index] > '9') {
return null;
}
// result = result * 10 + c[index] - '0';
result = (result.multiply(BigInteger.valueOf(10))).add(BigInteger
.valueOf(c[index] - '0'));
index++;
}
if (flag == false) {
// result *= -1;
result = result.divide(BigInteger.valueOf(-1));
}
return result;
}
}