[Codility] Time Complexity - FrogJmp 풀이
예문
https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
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 = 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.
해석
- 개구리는 길 건너편으로 가길 원함.
- X : 현재 위치
- Y : 타겟 위치
- 개구리는 현재 위치 X 에서 Y 보다 크거나 같은 위치로 가길 원함
- 개구리는 항상 고정된 거리 D 만큼 점프
- 개구리가 Y에 도달하는 최소 횟수를 리턴하라!
풀이
- (Y - X) / D
- 소수점은 올림 처리
제약사항
- X, Y, D의 범위는 정수 [1..1,000,000,000]
- X ≤ Y
코드
public int solution(int X, int Y, int D) {
double divideNum = (Y - X) * 1.0 / D; //double 형 변환을 위해 1.0 곱함.
return (int) Math.ceil(divideNum); //올림 처리
}