본문 바로가기

코딜리티 문제풀이

Codility Lesson 03 - FrogJmp( JAVA )

https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/

 

FrogJmp coding task - Learn to Code - Codility

Count minimal number of jumps from position X to Y.

app.codility.com

문제

- frog는 X위치에서 Y위치 또는 그보다 더 상위로 가는게 목표다.

- frog는 정해진 D만큼만 이동할 수 있다.

- 목적지에 도달하기 위한 최소한의 jump수를 구하라.

제한조건

  • X, Y and D are integers within the range [1..1,000,000,000];
  • X ≤ Y.

X, Y, D는 1 ~ 1,000,000,000 범위 안의 정수이다.

X <= Y

 

풀이

- Integer의 범위 : -2,147,483,648 ~ 2,147,483,647

- Y가 Integer의 범위안에 있으므로 변수를 int로 해도 무방할듯하다.

- D가 0인 경우가 없으므로 예외 케이스를 두지 않아도 된다.( 횟수는 나오게 되어 있다. )

- Y와 X의 간격을 D간격으로 뛰는 것이기에 ( Y - X ) / D로 풀이를 접근한다.

- gap = Y - X, gap이 D로 나누어 떨어지는 경우와 그렇지 않은 경우로 분기하여 풀이

 

소스코드

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int X, int Y, int D) {
        // write your code in Java SE 8

        int gap = Y - X;
        int cnt = gap / D;

        // 나누어 떨어지지 않을 경우
        if( gap % D != 0 ){
            cnt += 1;
        }

        return cnt;
    }
}