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.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, 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 = 40after the second jump, at position 10 + 30 + 30 = 70after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:
X, Y and D are integers within the range [1..1,000,000,000];X ≤ Y.
class Solution {
public int solution(int X, int Y, int D) {
int result = 0;
// X값에서 시작해 Y값 이상을 넘을 경우의 횟수를 구하기 위해서
// Y값 에서 X 값을 뺀 semi값이 D를 몇번 반복해야 넘을 수 있는지 파악해야 한다.
int semi = Y-X;
// result 에 semi 값을 나눗 몫이 D를 반복한 횟수가 될 것
result = semi/D;
// semi 에 D를 나눈 나머지값이 존재하면 아직 넘지못하고 한번 더 넘어야 하고
// 나머지값이 0인경우 마지막자리에 도달한 것이기에 한던 더 넘지 않아도 된다.
result = semi%D==0 ? result : result + 1;
return result;
}
}
'algorithm > Codility' 카테고리의 다른 글
Codility[Lesson 3] - Time Complexity(TapeEquilibrium) (0) | 2021.08.26 |
---|---|
Codility[Lesson 3] - Time Complexity(PermMissingElem) (0) | 2021.08.26 |
Codility[Lesson 2] - Arrays(OddOccurrencesInArray) (0) | 2021.08.08 |
Codility[Lesson 2] - Arrays(CyclicRotation) (0) | 2021.08.08 |
Codility[Lesson 1] - Iterations (BinaryGap) (0) | 2021.08.08 |
댓글