在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所需的跳跃,这是青蛙想要到达的位置。我没有正确理解问题?如果是这样,我想念的是什么?
答案 0 :(得分:0)
您正在使用条件
while(X <= Y)
进行新的跳转。但是,在X == Y
的情况下,您已经达到了目标,并且不想进一步前进。因此,更新为
while(X < Y) //as long as we have not reached the goal
答案 1 :(得分:0)
这是我的解决方案。您的距离计算为Y-X。因此,您只需要划分并检查除数即可:
function solution(X,Y,D) {
var distance = Y-X;
var steps = distance/D;
/* If steps number is rounded integer just return steps */
if((steps*D) == distance && Number.isInteger(steps)) {
return steps;
} else {
/* if there is rest of division then just round it (to floor) and increase steps number for one */
return Math.floor(steps)+1;
}
}
console.log(solution(10,85,30)); /* 3 */
这是JavaScript的解决方案,复杂度基本上是O(1)。
答案 2 :(得分:0)
为什么在这里使用任何循环,循环是一件昂贵的事情。只需一行答案
function solution(X,Y,D) {
return Math.ceil((Y-X)/D);
}