도라에몽주머니

[Codility/Java] 문제 4. FrogJmp 본문

Algorithm

[Codility/Java] 문제 4. FrogJmp

에몽쓰 2022. 11. 22. 20:20

FrogJmp

 

Task

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.

 

Solution

class Solution {
    public int solution(int X, int Y, int D) {
        int dist = Y - X;
        int result = 0;

        if(dist <= 0) result = 0;
        if(dist%D == 0) result = dist/D;
        else result = dist/D + 1;

        return result;
    }
}

 

Notes

처음에는 Y가 X보다 작거나 같은 경우를 고려하지 못해서 정확도가 88%밖에 되지 않았다.

코드를 제출하고 문제를 발견해 다시 정확도를 100%로 올렸지만 FrogJmp 같은 비교적 단순한 문제는 실수를 줄이도록 예외처리에 좀 더 신경써야겠다.