forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0338-counting-bits.cs
More file actions
35 lines (31 loc) · 789 Bytes
/
0338-counting-bits.cs
File metadata and controls
35 lines (31 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
public int[] CountBits(int n) {
var hammingWeights = new int[n+1];
for (int i = 0; i <= n; i++)
{
var binary = Convert.ToString(i, 2);
var hammingWeight = 0;
for (int j = 0; j < binary.Length; j++)
{
hammingWeight += binary[j] - '0';
}
hammingWeights[i] = hammingWeight;
}
return hammingWeights;
}
// With dp
public int[] CountBits(int n)
{
var dp = new int[n + 1];
var offset = 1;
for (int i = 1; i < n + 1; i++)
{
if (offset * 2 == i)
{
offset = i;
}
dp[i] = 1 + dp[i - offset];
}
return dp;
}
}