Codility - FlogJmp
Task description
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 = 30the 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
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) {
// 점프 횟수 jmpCnt = Math.ceil(가야할 거리 / D)
// 예를들어 3.5번을 뛰어야한다면, Y와 같아지지도 않을 뿐더러
// 한번더 뛰어서 4번을 뛰어야만 Y이상이 되기 때문
int dist = Y - X;
if(dist<=0) return 0;
return (int) Math.ceil((double) dist / D);
}
}
1. 풀이 전략
1) 반복문으로 코딩하면, 점프횟수가 매우 클 경우(1~10억의 범위) runtime error가 발생함
2) O(1)의 시간 복잡도로 해결
3) 결국 점프횟수는 가야할거리 / D를 무조건 올린 수 이다.
(예를들어 3.5번 점프해야한다면, 1번을 더 점프해서 4번을 점프해야, Y 이상이 되기 때문)
4) Math.ceil() 함수는 위 코드에서 double타입으로 리턴하기 때문에, (int)로 casting해서 결과값을 리턴한다.