[Codility] 3. Time Complexity | 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

๋ฌธ์ œ๋Š” ๊ธธ~๊ฒŒ ์„ค๋ช…๋˜์–ด์žˆ์ง€๋งŒ ์•„์ฃผ ๊ฐ„๋‹จํ•œ 1์ฐจ ๋ถ€๋“ฑ์‹์œผ๋กœ ์ •๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

a = ์ ํ”„์ˆ˜
Y โ‰ค X+aD

โˆด a โ‰ฅ (Y-X)/D

์œ„ ๋ถ€๋“ฑ์‹์„ ํ™œ์šฉํ•˜๋ฉด ์•„์ฃผ ๊ฐ„๋‹จํ•œ ์ฝ”๋“œ๊ฐ€ ์™„์„ฑ๋ฉ๋‹ˆ๋‹ค!

class Solution {
	public int solution (int X, int Y, int D){
    	return (int) Math.ceil((Y-X)/(D*1.0));
	}
}

๐Ÿ’ฌ Note

  1. ๊ณ„์‚ฐ ๊ฒฐ๊ณผ์˜ ์†Œ์ˆ˜์ ์„ ๋ณด์กดํ•˜๊ธฐ ์œ„ํ•ด double๋กœ ๋ณ€ํ™˜ํ•˜๊ณ ์ž 1.0์„ ๊ณฑํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค. ๋ช…์‹œ์  ํ˜•๋ณ€ํ™˜์„ ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.
Math.ceil((Y-X)/(D * 1.0));	//๋ฌต์‹œ์  ํ˜•๋ณ€ํ™˜
Math.ceil((Y-X)/(double) D);	//๋ช…์‹œ์  ํ˜•๋ณ€ํ™˜
  1. Y ์ด์ƒ์˜ ๊ฐ’์„ ์ฐพ๊ธฐ ์œ„ํ•ด Math class์˜ ์–ด๋ฆผ ํ•จ์ˆ˜ ์ค‘ ์˜ฌ๋ฆผ์„ ์‚ฌ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

    FunctionDescriptionExample
    Math.around()๋ฐ˜์˜ฌ๋ฆผMath.around(1.1) => 1.0
    Math.around(1.9) => 2.0
    Math.ceil()์˜ฌ๋ฆผMath.ceil(1.1) => 2.0
    Math.floor()๋‚ด๋ฆผMath.floor(1.9) => 1.0

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ