-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting_bits.cpp
50 lines (43 loc) · 1.03 KB
/
counting_bits.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// https://leetcode.com/problems/counting-bits/
// May 28, 2016
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> countBits(int num)
{
vector<int> vecBitCount;
// initialize with zeros
for (int i=0; i != (num+1); ++i)
{
vecBitCount.push_back(0);
}
// 2^r has single 1 bit
vecBitCount[0] = 0; // For int i=0
int r = 1;
while (r <= num)
{
vecBitCount[r] = 1; // r is power of 2
int i = 1;
while ((i < r) && ((r+i) <= num))
{
vecBitCount[r+i] = vecBitCount[r] + vecBitCount[i];
++i;
}
r *= 2;
}
return vecBitCount;
}
};
int main(int argc, char* argv[])
{
int num = 0;
Solution sln;
vector<int> vecBitCount = sln.countBits(num);
for (vector<int>::iterator it = vecBitCount.begin(); it != vecBitCount.end(); ++it)
{
cout << *it << ",";
}
return 0;
}