File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ PROBLEM:
2+
3+
4+ Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1' s in their
5+ binary representation and return them as an array.
6+
7+ Example 1 :
8+ Input: 2
9+ Output: [0 ,1 ,1 ]
10+
11+ Example 2 :
12+ Input: 5
13+ Output: [0 ,1 ,1 ,2 ,1 ,2 ]
14+
15+ Follow up:
16+
17+ 1 . It is very easy to come up with a solution with run time O (n*sizeof (integer)). But can you do it in linear time
18+ O(n) /possibly in a single pass?
19+ 2. Space complexity should be O(n).
20+ 3. Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
21+
22+
23+
24+
25+ SOLUTION:
26+
27+
28+
29+ class Solution {
30+ public:
31+ vector<int > countBits (int num) {
32+
33+ int i;
34+
35+ vector<int > v;
36+
37+ for (i=0 ;i<=num;i++)
38+ {
39+ v.push_back (__builtin_popcount (i));
40+ }
41+
42+
43+ return v;
44+ }
45+ };class Solution {
46+ public:
47+ vector<int > countBits (int num) {
48+
49+ int i;
50+
51+ vector<int > v;
52+
53+ for (i=0 ;i<=num;i++)
54+ {
55+ v.push_back (__builtin_popcount (i));
56+ }
57+
58+
59+ return v;
60+ }
61+ };
You can’t perform that action at this time.
0 commit comments