java - 如何修复“Codility FrogJump”算法?
问题描述
在 Codility 上,有一个计算青蛙到达 Y 位置所需的最少跳跃次数的问题。
问题如下:
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
我已经“解决”了这个问题并得到了“3”,就像在这个例子中一样。然而,当我提交我的代码时,我只得到 11% 并且除了示例之外的所有测试都失败了。
这是我的代码
int count = 0;
while(X <= Y){
X += D;
count++;
}
return count;
在我的代码中,我基本上计算了到达 Y 所需的跳跃次数,这是青蛙想要到达的位置。我没有正确理解这个问题?如果是这样,我错过了什么?
解决方案
为什么在这里使用任何循环,循环是一件昂贵的事情。只需一行答案
function solution(X,Y,D) {
return Math.ceil((Y-X)/D);
}
推荐阅读
- javascript - 为什么要在 app.module.ts 中导入 { HttpClientModule }
- php - PHP-MySQL:多文件上传代码中的第一个文件未上传到服务器
- r - 尝试格式化ggplot输出
- python - Python - 多处理卡住
- python - 对多个 csv 文件重复相同的过程
- java - 在 JShell 中使用 final 变量
- laravel - laravel 门面如何同时使用数据库和数据库实例?
- python - SARIMAX 预测平均输出
- javascript - 在 django 框架中使用 javascript 插件进行图像缩放/放大
- angular - 如何将自定义组件注册为有效、无效、脏、已触摸等