codility-3-2-FrogJmp

FrogJmp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29


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:

function solution(X, Y, 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.

Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

설명

X : 시작 위치
Y : 도착 위치
D : 증가량

X+nD > Y의 n을 구하기
도착위치에서 시작위치를 뺀 후 증가량 D로 나누기
다른 언어의 경우 기본적으로 정수형 연산이기 때문에 나머지가 있으면 몫+1 이지만
javascript는 기본적으로 모든 숫자의 연산이 정수가 아닌 실수형이기 때문에 올림으로 계산하면 됨

코드

1
2
3
4
function solution(X, Y, D) {
// write your code in JavaScript (Node.js 8.9.4)
return Math.ceil((Y - X) / D);
}

결과

image

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×