Skip to content

Commit 54570ec

Browse files
authored
[28 May, 2020] Add cpp solution2 and solution3
1 parent c7bc6e7 commit 54570ec

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

May-LeetCoding-Challenge/28-Counting-Bits/Counting-Bits.cpp

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,47 @@ class Solution {
1212
}
1313
return ans;
1414
}
15-
};
15+
};
16+
17+
class Solution2 {
18+
public:
19+
inline int numberOfSetBits(int i)
20+
{
21+
i = i - ((i >> 1) & 0x55555555);
22+
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
23+
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
24+
}
25+
26+
vector<int> countBits(int num) {
27+
vector<int> v;
28+
for (int i = 0; i <= num ; ++i)
29+
v.push_back(numberOfSetBits(i));
30+
return v;
31+
}
32+
};
33+
34+
class Solution3 {
35+
public:
36+
vector<int> countBits(int num) {
37+
vector<int> v(num+1);
38+
int n = 1, src = 0;
39+
40+
/* init */
41+
v[0] = 0;
42+
43+
while ((n<<1)+n <= num) {
44+
for (;src<n;++src) v[src+n] = v[src]+1;
45+
n += n;
46+
memcpy(&v[n], &v[src], (n-src)*sizeof(int));
47+
}
48+
49+
if (num < n*2) {
50+
for (;src<=num-n;++src) v[src+n] = v[src]+1;
51+
return v;
52+
}
53+
for (;src<n;++src) v[src+n] = v[src]+1;
54+
n += n;
55+
memcpy(&v[n], &v[src], (num-n+1)*sizeof(int));
56+
return v;
57+
}
58+
};

0 commit comments

Comments
 (0)