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)