본문 바로가기

Study/Codility

[JAVA] Codility Lesson 3(1) - Time Complexity : FrogJmp

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

 

 

Tasks


작은 개구리가 점프해야하는 횟수 구하기 
현재 작은 개구리가 있는 곳을 X,
작은 개구리가 도착하거나 지나가야 하는 곳을 Y,
작은 개구리가 한 번 점프해서 갈 수 있는 거리 D 라고 했을 때, 
주어진 정수 X, Y, D를 이용하여 최소 점프 횟수를 맞추기
ex)
-----------------------------------------------
 int X = 10, int Y = 85, int D = 30
 10 + 30 = 40
 40 + 30 = 70
 70 + 30 = 100
 최종 결과 3 반환
-----------------------------------------------

 

Solution


public static int solution(int X, int Y, int D) {
    int answer = 0;

    while (X < Y)
    {
        X += D;
        answer++;

    }

    return answer;
}

 

TIMEOUT ERROR 발생...

while문 때문에 발생한 것 같다.. 

이중for문도 아닌데...

반복문을 사용하면 안될 것 같아 새로 변경한 코드

 

 

public static int solution(int X, int Y, int D) {
    int answer = 0;

    if ( X < Y ) {
        answer = (Y-X)/D;

        if ( (Y-X)%D > 0 ) answer++;
    }

    return answer;
}