forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSetBits_Efficient_Solution.cpp
More file actions
66 lines (50 loc) · 1.58 KB
/
CountSetBits_Efficient_Solution.cpp
File metadata and controls
66 lines (50 loc) · 1.58 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Program -> To count set bits in a number
//Given a number. Count number of set-bits in binary-representation of that number
/*
There are several methods to do so.
(1) Simple (Naive) Method -
Check every bit one by one if it is set or not
So Time-Complexity = O(Total bits in number)
(2) Better Solution -
(Using Brian Kerningam's Algorithm)
Time-Comlexity = O(Count of set-bits in number)
(3) Efficient Solution -
Look-up table method ->
Time-Complexity = O(1)
But it requires some preprocessing.
Here, We divide our input (let's assume - 64-bit no.) into 8 chunks of 8-bits each.
Precompute set bits in these chunks then use these results in our input in O(1) time.
*/
//So Solution 3 -
//Lookup Table Method ->
#include <iostream>
using namespace std;
int setBitsTable[256];
//Because 8-bits chunks. So size = 0 -> ((2^8)-1) = 0 -> 255
void preprocessingOfChunks()
{
setBitsTable[0] = 0;
for(int index=1 ; index<256 ; index++)
setBitsTable[index] = (index & 1) + setBitsTable[index/2];
}
int countSetBits (int number)
{
//For 64-bit representation - 8 chunks of 8-bits each
//For 32-bit representation - 4 chunks of 8-bits each
//Here we solve considering 64-bit representation
int result = setBitsTable[number & 0xff]; //0xff = Binary Representation - 11111111
for(int tempCount=1 ; tempCount<8 ; tempCount++)
{
number = number >> 8;
result += setBitsTable[number & 0xff];
}
return result;
}
int main()
{
preprocessingOfChunks(); //For Pre-processing
int number;
cin>>number;
cout<<"The Number of set-bits in "<<number<<" is = "<<countSetBits(number)<<endl;
return 0;
}