题解 | #牛群全排列数# java
牛群全排列数
https://www.nowcoder.com/practice/5ab233c23fcc4c69b81bd5a66c07041c
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
static final int mod = 1000000007;
public int factorial(int n) {
// write code here
// 全排列 算阶乘 -- n的范围在10^6
if (n == 1)
return 1;
long ret = 1;
for (int i = 2; i <= n; i++) {
ret = (ret * i) % mod;
}
return (int)ret;
}
}
编程语言是Java。
该题考察的知识点是计算阶乘。
代码的文字解释:
factorial方法,接受一个整数n作为参数,并返回n的阶乘。- 判断如果
n等于1,则直接返回1。 - 创建一个名为
ret的长整型变量并初始化为1。 - 从2开始循环遍历到
n,每次将ret与i相乘,并对mod取模,更新ret的值。 - 最后将
ret转换为整型,并返回结果。
查看7道真题和解析