4 回答

TA贡献1826条经验 获得超6个赞
它应该是:
public static long fallingPower(int n, int k){
long result = n;
for (int i = 0; i < k; i++) {
n=n-1;
result = result * n;
}
return result;
}

TA贡献2011条经验 获得超2个赞
public static long fallingPower(int n, uint k){
long result = 1;
for(; k > 0; k--, n--){
result *= n;
}
return result;
}

TA贡献1809条经验 获得超8个赞
你应该乘以k时间,从每个因子开始n并递减一个。您的代码目前没有任何意义。我会这样做:
public static long fallingPower(int n, int k)
long result = n;
for (int i = 1; i < k; i++) {
result = result * (n-i);
}
return result;
}
k必须是非负的,所以你也需要在方法中处理它,例如有一个例外:
public static long fallingPower(int n, int k)
if(k < 0) {
throw new IllegalArgumentException("Negative exponent");
}
long result = n;
for (int i = 1; i < k; i++) {
result = result * (n-i);
}
return result;
}

TA贡献1813条经验 获得超2个赞
如果我没记错的话,这更多的是编程逻辑,而不是你的方法。我没有错误处理。我开始像你一样倒退,假设零的最小整数排列等于 1,至少我们需要返回 1。你可以从 n 之前的 k 个数字开始,然后乘以直到达到 n。
public static long fallingPower(int n, int k)
{
long result = 1;
for (int i = 1 ; i <= k ; i++) {
result = result * n;
n = n-1;
}
return result;
}
添加回答
举报