求任一正整数的阶乘(注意:是任意正整数)
该正整数不大于1000。
import java.util.*;
public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(new Main().factorial(n)); }
//这个题是大数的阶乘,如果使用一般类型是不行的,这里我们先实现相乘
public String MultiplicationStr (String first, String second) {
//受限字符串必须都是数字[0-9]+,并且至少出现一次
String regEx = "^[0-9]+$";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(first);
Matcher matcher1 = pattern.matcher(second);
if(!matcher.matches() || !matcher1.matches()) {
return "-1";
}
//数据校验通过,然后我们开始进行相乘操作
String result = "0";
int b10 = 0;
//我们取最长的那个
long upNum = 0;
for(int i = first.length() - 1; i >= 0; --i) {
//遍历这个字符
long temp1 = Long.valueOf(first.charAt(i) + "");
String tmpResultStr = "";
for(int j = second.length() - 1; j >= 0; --j) {
long temp2 = Long.valueOf(second.charAt(j) + "");
//这里要考虑进位
long tempResult = temp1 * temp2 + upNum;
upNum = tempResult / 10;
long curNum = tempResult % 10;
tmpResultStr = curNum + tmpResultStr;
}
//添加进位数
if(upNum > 0) {
tmpResultStr = upNum + tmpResultStr;
upNum = 0;
}
//添加10的倍数
for(int b = 0; b < b10; ++b) {
tmpResultStr += "0";
}
++b10;
if(tmpResultStr.equals("")) {
tmpResultStr = "0";
}
result = this.add(result, tmpResultStr);
}
//我们最后还要把进位的加上,这里考虑
// if(upNum > 0) {
// result = upNum + result;
// }
return result;
}
/**
*
* @program: y2019.m03.d22.FactorialNum
* @description: 字符相加
* @auther: xiaof
* @date: 2019/3/22 20:14
*/
public String add(String num1, String num2) {
String regEx = "^[0-9]+$";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(num1);
Matcher matcher1 = pattern.matcher(num2);
if(!matcher.matches() || !matcher1.matches()) {
return "0";
}
//相加
int i = num1.length() - 1, j = num2.length() - 1, index = num1.length() > num2.length() ? num1.length() : num2.length();
int upNum = 0;
String result = "";
for(; index > 0; --i,--j, --index) {
//获取当前位阶的数据
int n1 = 0;
int n2 = 0;
if(i >= 0) {
n1 = Integer.valueOf(num1.charAt(i) + "");
}
if(j >= 0) {
n2 = Integer.valueOf(num2.charAt(j) + "");
}
int tempSum = n1 + n2 + upNum;
upNum = tempSum / 10;
int curNum = tempSum % 10;
result = String.valueOf(curNum) + result;
}
//最后计算剩余的长度值
if(upNum > 0) {
result = upNum + result;
}
return result;
}
public String factorial (int n) {
if(n == 0) {
return "0";
}
if(n == 1) {
return "1";
}
String result = "1";
for(int i = 2; i <= n; ++i) {
result = this.MultiplicationStr(result, i + "");
}
return result;
}
}