๐ฐ์ด๋ณด์ ์นํ ๊ฐ์ด๋ 'Prime Number of Set Bits in Binary Representation' - Problem 762 (C++, Python, JavaScript)
Source: Dev.to
Problem Summary
์ฃผ์ด์ง ์
๋ ฅ:
๋ ์ ์ left์ right๊ฐ ์ฃผ์ด์ง๋ฉฐ, ์ด๋ ํฌํจ ๊ตฌ๊ฐ์ ์ ์ํฉ๋๋ค.
๋ชฉํ:
๊ทธ ๊ตฌ๊ฐ ์์ ์๋ ์ซ์๋ค ์ค, ์ด์ง ํํ์์ 1์ ๊ฐ์(=โฏset bit) ๊ฐ ์์์ธ ์ซ์์ ๊ฐ์๋ฅผ ๊ตฌํฉ๋๋ค.
Intuition: How it Works
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ๊ตฌ๊ฐ์ ๊ฐ ์ซ์์ ๋ํด ๋ ๊ฐ์ง ์์ ์ ์ํํฉ๋๋ค:
-
set bit ๊ฐ์ ์ธ๊ธฐ.
์์:6โ ์ด์ง์110โ set bit =2. -
๊ทธ ๊ฐ์๊ฐ ์์์ธ์ง ํ์ธํ๊ธฐ.
์์๋ 1๋ณด๋ค ํฐ ์์ฐ์์ด๋ฉฐ 1๊ณผ ์๊ธฐ ์์ ์ธ์๋ ์ฝ์๊ฐ ์๋ ์์ ๋๋ค.
right โค 10โถ์ด๋ฏ๋ก ์ต๋ set bit ๊ฐ์๋ ์ฝ 20 ์ ๋์ด๋ฉฐ, ์์ ํ๋ณ์ ๋งค์ฐ ๊ฐ๋จํฉ๋๋ค.
Walkthrough: Understanding the Example
left = 6์ด๊ณ right = 10์ธ ๊ฒฝ์ฐ:
| Number | Binary | Set bits | Prime? |
|---|---|---|---|
| 6 | 110 | 2 | Yes |
| 7 | 111 | 3 | Yes |
| 8 | 1000 | 1 | No |
| 9 | 1001 | 2 | Yes |
| 10 | 1010 | 2 | Yes |
์ด ๊ฐ์: 4
The Solutions
C++ Implementation
class Solution {
public:
// Helper function to check if a number is prime
bool isPrime(int x) {
if (x int:
def is_prime(x: int) -> bool:
if x {
if (x < 2) return false;
for (let i = 2; i * i <= x; i++) {
if (x % i === 0) return false;
}
return true;
};
let ans = 0;
for (let i = left; i <= right; i++) {
// Convert to binary string and count '1's
let setBits = i.toString(2).split('1').length - 1;
if (isPrime(setBits)) {
ans++;
}
}
return ans;
};
Python Implementation
def is_prime(x: int) -> bool:
if x {
JavaScript Implementation
let ans = 0;
for (let i = left; i <= right; i++) {
// Convert to binary string and count '1's
let setBits = i.toString(2).split('1').length - 1;
if (isPrime(setBits)) {
ans++;
}
}
return ans;
Key Takeaways
- ๋นํธ ์กฐ์: ์ด์ง ํํ์ ์ดํดํ๋ ๊ฒ์ ํจ์จ์ ์ธ ์ฝ๋๋ฅผ ์์ฑํ๋ ๋ฐ ๊ธฐ๋ณธ์ด ๋ฉ๋๋ค.
- ํฌํผ ํจ์:
isPrime์ ๊ฐ์ ๋ก์ง์ ๋ณ๋ ํจ์๋ก ๋ถ๋ฆฌํ๋ฉด ๊ฐ๋ ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ด ํฅ์๋ฉ๋๋ค. - ์ธ์ด๋ณ ์ ํธ๋ฆฌํฐ: ๊ฐ ์ธ์ด๋ ๋นํธ๋ฅผ ๋ค๋ฃจ๋ ํธ๋ฆฌํ ๋ฐฉ๋ฒ์ ์ ๊ณตํฉ๋๋คโC++์
__builtin_popcount, Python์bin, JavaScript์toString(2)๋ฑ.
Final Thoughts
์ด ๋ฌธ์ ๋ ๊ธฐ๋ณธ์ ์ธ ๋นํธ ์ฐ์ฐ์ ์๊ฐํฉ๋๋ค. ๊ฒ๋ณด๊ธฐ์ ๊ฐ๋จํ ์ํ ํผ์ฆ์ฒ๋ผ ๋ณด์ด์ง๋ง, ๋นํธ๋ฅผ ์ธ๊ณ ์กฐ์ํ๋ ๋ฅ๋ ฅ์ ์ํธํ์ด๋ ์์ถ ๋ฐ์ดํฐ ๊ตฌ์กฐ์ ๊ฐ์ ๋ถ์ผ์์ ๋งค์ฐ ์ค์ํฉ๋๋ค. ์ด๋ฌํ ๊ธฐ์ด๋ฅผ ๋ง์คํฐํ๋ฉด ์๋์ด ์์ค์ ์์ง๋์ด๋ง ์ธํฐ๋ทฐ์์ ์์ฃผ ๋ฑ์ฅํ๋ ๋ณต์กํ โ๋นํธ๋ง์คํฌโ ๋ฌธ์ ๋ค์ ํด๊ฒฐํ๋ ๋ฐ ํฐ ๋์์ด ๋ฉ๋๋ค.