๋ฌธ์
Write a function:
public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
Write an efficient algorithm for the following assumptions:
A and B are integers within the range [0..2,000,000,000];
K is an integer within the range [1..2,000,000,000];
A ≤ B.
๋ฌธ์ ๋งํฌ
CountDiv coding task - Learn to Code - Codility
Compute number of integers divisible by k in range [a..b].
app.codility.com
GitHub
GitHub - yoohyebin/swift
Contribute to yoohyebin/swift development by creating an account on GitHub.
github.com
๋ฌธ์ ๋ถ์
- ์ ์ A, B, K๊ฐ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ค.
- A๋ถํฐ B๊น์ง ์ฌ์ด์ ์ ์๋ค ์ค K๋ก ๋๋์ด ๋จ์ด์ง๋ ์ ์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
ex) A = 6, B = 11, K = 2
[6...11] = 6, 7, 8, 9, 10, 11
์ด ์ ์๋ค ์ค 2(K)๋ก ๋๋์ด ๋จ์ด์ง๋ ์๋ 6, 8, 10์ด๋ค.
๋ฐ๋ผ์ ์ ๋ต์ 3์ด๋ค.
ํด๊ฒฐ๋ฐฉ์
- B๋ฅผ K๋ก ๋๋ ๋ชซ์์ A๋ฅผ K๋ก ๋๋ ๋ชซ์ ๋นผ๊ธฐ
- 0๋ถํฐ N๊น์ง ๋ฒ์ ์ค K๋ก ๋๋์ด ๋จ์ด์ง๋ ์ ์์ ๊ฐ์๋ฅผ ๊ตฌํ ๋ N์ K๋ก ๋๋ ๋ชซ์ ๊ตฌํ๋ฉด ๋๋ค.
- A๋ถํฐ B๊น์ง์ ๋ฒ์์์ K๋ก ๋๋์ด ๋จ์ด์ง๋ ์ ์์ ๊ฐ์๋ฅผ ๊ตฌํ ๋๋ 0๋ถํฐ B๊น์ง ์์ 0๋ถํฐ A๊น์ง K๋ก ๋๋์ด ๋จ์ด์ง๋ ์ ์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ฉด ๋๋ค.
- A๊ฐ K๋ก ๋๋์ด ๋จ์ด์ง๋ค๋ฉด re ๋ณ์๋ฅผ 1 ์ฆ๊ฐ
Solution
public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int {
let re = B/K - A/K
return A%K == 0 ? re + 1 : re
}
- ์๊ฐ ๋ณต์ก๋: O(1)
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ๋จธ์ฑ์ด๋ณด๋ค ํค ํฐ ์ฌ๋ (1) | 2022.11.29 |
---|---|
[Swift] ํ๋ก๊ทธ๋๋จธ์ค LV.0 ์ค๋ณต๋ ์ซ์ ๊ฐ์ (0) | 2022.11.29 |
[Swift] Codility Lesson 5 - PassingCars (0) | 2022.07.26 |
[Swift] Codility Lesson 4 - MissingInteger (0) | 2022.07.24 |
[Swift] Codility Lesson 4 - MaxCounters (0) | 2022.07.23 |