求一个数的阶乘,并将其转换成16进制数格式的字符串(0-9,A-F,注意:要求字母大写)作为结果输出(优化,前一篇考虑的太原生化,有现成的字符串进制转换函数可以使用,以后要切记!)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
while (num != -1) {
long facResult = fac(num);
String ans = "";
// 方案一
ans = Long.toUnsignedString(facResult, 16);
System.out.print("其16进制:" + ans.toUpperCase() + "; ");
// 方案二
ans = Long.toHexString(facResult);
System.out.print("其16进制:" + ans.toUpperCase() + ";");
ans = Long.toBinaryString(facResult);
System.out.print(num + "的阶乘:" + facResult + ";其2进制:" + ans + ";");
num = sc.nextInt();
}
}
// 求阶乘
public static long fac(int n) {
if (n == 0) {
return 1;
} else {
return n * fac(n - 1);
}
}
}
运行结果截图: