Skip to content

Commit c397bed

Browse files
committed
feat: counting-bits
1 parent 3031884 commit c397bed

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

β€Žcounting-bits/invidam.go.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
Β (0)