|
| 1 | +# Intuition |
| 2 | +<!-- Describe your first thoughts on how to solve this problem. --> |
| 3 | +์ด์ ๊ฐ๋ค์ ์ฌํ์ฉํ๋ค. |
| 4 | +# Approach |
| 5 | +<!-- Describe your approach to solving the problem. --> |
| 6 | +1. ์ฃ์ง ์ผ์ด์ค๋ 0์ ๋ฐํํ๋ค. |
| 7 | +2. 0, 1์ ๋ฏธ๋ฆฌ ๊ณ์ฐํ๋ค. |
| 8 | +3. `>>`์ ์ํํ ๊ฒฐ๊ณผ + ์ง/ํ ์ฌ๋ถ๋ก ์ธํ 1์ ๋ํด์ ํด๊ฒฐํด์ค๋ค. |
| 9 | +- ์ด์ง์ `1001`์ ๊ฒฝ์ฐ `100` ๊ณ์ฐํ ๊ฒฐ๊ด๊ฐ์์ `1`์ ๋ํด์ฃผ๋ฉด ๋๋ค. |
| 10 | +- ์ด์ง์ `1010`์ ๊ฒฝ์ฐ `101` ๊ณ์ฐํ ๊ฒฐ๊ด๊ฐ์์ `0`์ ๋ํด์ฃผ๋ฉด ๋๋ค. |
| 11 | + |
| 12 | +- ์๋ฃจ์
์ฐธ๊ณ : `i & (i-1)` ์ฐ์ฐ์ ํตํด ๊ณ์ฐํ๋ค. |
| 13 | + - 2์ ์ ๊ณฑ์์ธ ๊ฒฝ์ฐ `0`์ด ๋์ 1์ ๋ํ๋ฉด ๋๋ค. |
| 14 | + - ์๋ ๊ฒฝ์ฐ๋ ์์ง์ ์ ๋ชจ๋ฅด๊ฒ ๋ค. |
| 15 | +# Complexity |
| 16 | +- Time complexity: $$O(n)$$ |
| 17 | +<!-- Add your time complexity here, e.g. $$O(n)$$ --> |
| 18 | +:`n`ํฌ๊ธฐ์ ๋ฐฐ์ด์ ๋ชจ๋๋ฅผ ์ํํ๋ค. |
| 19 | +- Space complexity: $$O(n)$$ |
| 20 | +<!-- Add your space complexity here, e.g. $$O(n)$$ --> |
| 21 | +:ํฌ๊ธฐ `n`์ ๋ฐฐ์ด์ ์ ์ธํ๋ค. |
| 22 | +# Code |
| 23 | +```go |
| 24 | +func countBits(n int) []int { |
| 25 | + if n == 0 { |
| 26 | + return []int{0} |
| 27 | + } |
| 28 | + ans := make([]int, n+1, n+1) |
| 29 | + |
| 30 | + ans[0], ans[1] = 0, 1 |
| 31 | + |
| 32 | + for i := 2; i <= n; i++ { |
| 33 | + ans[i] = ans[i>>1] + i&1 |
| 34 | + } |
| 35 | + return ans |
| 36 | +} |
| 37 | + |
| 38 | +func countBitsSolution(n int) []int { |
| 39 | + res := make([]int, n+1) |
| 40 | + for i := 1; i <= n; i++ { |
| 41 | + res[i] = res[i&(i-1)] + 1 |
| 42 | + } |
| 43 | + return res |
| 44 | +} |
| 45 | +``` |
0 commit comments