Java 实现大整数阶乘计算,并处理异常情况
import java.math.BigInteger;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数:");
String input = scanner.nextLine();
try {
BigInteger num = new BigInteger(input);
BigInteger result = factorial(num);
System.out.println(num + "! = " + result);
} catch (NumberFormatException e) {
try {
int hexIndex = input.indexOf('x');
if (hexIndex != -1) {
String hexStr = input.substring(hexIndex + 1);
BigInteger num = new BigInteger(hexStr, 16);
BigInteger result = factorial(num);
System.out.println(hexStr + "! = " + result);
} else {
System.out.println("输入不是一个整数!");
}
} catch (NumberFormatException ex) {
System.out.println("输入不是一个整数!");
}
}
}
public static BigInteger factorial(BigInteger n) {
if (n.compareTo(BigInteger.ZERO) == 0 || n.compareTo(BigInteger.ONE) == 0) {
return BigInteger.ONE;
} else {
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
}
}
原文地址: https://www.cveoy.top/t/topic/nqF8 著作权归作者所有。请勿转载和采集!