반응형
1. 문제
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:
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.
현재 위치(X)
목표 지점(Y)
한번에 이동 가능한 거리(D)
몇 번 이동해야 X에서 Y까지 갈 수 있는지 계산하는 문제
2. 풀이 전략
단순 계산이므로, 그냥 계산하면 된다. 수식으로 표현하자면 다음과 같다.
\( X + DN >= Y \) , (N은 점프 횟수)
\( DN >= Y - X \)
\( N >= \frac{Y - X}{D} \)
3. 코드 (C++)
int solution(int X, int Y, int D) {
if( ((Y - X) % D) == 0 ) return (Y - X) / D; //나머지가 없다면, 몫 만큼만 점프하면된다.
else return ((Y - X) / D) + 1; //나머지가 있다면, 한번 더 점프해야 한다.
}반응형
'Algorithm Problem > Codility' 카테고리의 다른 글
| Lesson 3. Time Complexity - TapeEquilibrium (1) | 2024.09.29 |
|---|---|
| Lesson 3. Time Complexity - PermMissingElem (0) | 2024.09.28 |
| Lesson 2. Arrays - OddOccurrencesInArray #2 (속도 개선) (0) | 2024.09.25 |
| Lesson 2. Arrays - OddOccurrencesInArray #1 (0) | 2024.09.25 |
| Lesson 2. Arrays - CyclicRotation (0) | 2024.09.21 |