๋ฌธ์
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:
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int
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.
๋งํฌ
FrogJmp coding task - Learn to Code - Codility
Count minimal number of jumps from position X to Y.
app.codility.com
๋ฌธ์ ๋ถ์
- ํ์ฌ ๊ฐ๊ตฌ๋ฆฌ์ ์์น X์์ Y์ด์๊น์ง ๊ฐ๊ธฐ ์ํด ๋ช ๋ฒ์ ์์ง์ฌ์ผ ํ๋์ง ๊ตฌํ๋ ๋ฌธ์ ๋ค.
- ๊ฐ๊ตฌ๋ฆฌ๊ฐ ํ ๋ฒ์ ๋ธ ์ ์๋ ๊ฑฐ๋ฆฌ๋ D๋งํผ์ด๋ค.
ex) X: 10, Y: 85, D: 30
1. 10 + 30 = 40
2. 40 + 30 = 70
3. 70 + 30 = 100
3๋ฒ์ ์ ํ๋ก 100๊น์ง ๊ฐ ์ ์๋ค (>= 85)
ํด๊ฒฐ๋ฐฉ์
- ๊ฐ๊ณ ์ถ์ ์์น์์ ํ์ฌ ์์น๋ฅผ ๋นผ๋ฉด ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ ์ ์๋ค.
- ๊ตฌํ ๊ฑฐ๋ฆฌ๋ฅผ ํ ๋ฒ์ ์์ง์ผ ์ ์๋ ๊ฑฐ๋ฆฌ๋ก ๋๋๋ฉด ์ด๋ํ๋๋ฐ ๊ฑธ๋ฆฌ๋ ํ์๋ฅผ ๊ตฌํ ์ ์๋ค.
- ๊ณ์ฐํ ์ด๋ ํ์๋งํผ ์ด๋ํ์ ๋, ๊ฐ๊ณ ์ถ์ ์์น์ ๋์ฐฉํ์ง ๋ชปํ๋ค๋ฉด 1์ ๋ํด์ค๋ค.
count = (Y-X)/D
// ๊ฐ๊ณ ์ถ์ ์์น์ ๋์ฐฉํ์ง ๋ชปํ ๊ฒฝ์ฐ
๋ง์ฝ (Y-X)% D ๊ฐ 0์ด ์๋๋ผ๋ฉด {
count = count + 1
}
Solution
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
return (Y-X)%D == 0 ? (Y-X)/D : ((Y-X)/D)+1
}
- ์๊ฐ ๋ณต์ก๋: O(1)
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] Codility Lesson 3 - TapeEquilibrium (0) | 2022.07.23 |
---|---|
[Swift] Codility Lesson 3 - PermMissingElem (0) | 2022.07.23 |
[Swift] Codility Lesson 2 - OddOccurrencesInArray (0) | 2022.07.23 |
[Swift] Codility Lesson2 - CyclicRotation (0) | 2022.07.23 |
[Swift] Codility Lesson1 - BinaryGap (0) | 2022.07.23 |