🔮문제
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.
🔮풀이
(Y-X)/D 만큼 점프하고 그래도 Y에 도달하지 못하면 (Y-X)/D + 1 만큼 점프한다.
단순하게 생각하기..!!!
🔮코드
#include <iostream>
int solution(int X, int Y, int D) {
int answer = 0;
if(X == Y){
return 0;
}
else if(X + D >= Y){
return 1;
}
else{
int diff = Y-X;
answer = diff/D;
if(diff%D != 0)
{
answer += 1;
}
return answer;
}
}
'코딩 테스트' 카테고리의 다른 글
[Codility] Lesson3. TapeEquilibrium (C++) (0) | 2021.02.23 |
---|---|
[Codility] Lesson3. PermMissingElem (C++) (0) | 2021.02.23 |
[Codility] Lesson1. BinaryGap (C++) (0) | 2021.02.23 |
[Codility] Lesson2. CyclicRotation (C++) (0) | 2021.02.22 |
[Codility] Lesson2. OddOccurrencesInArray (C++) (0) | 2021.02.22 |
댓글