Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions bit_manipulation/count_bit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <iostream>
using namespace std;

// Function to count total set bits from 1 to n
int countSetBits(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
int num = i;
while (num) {
count += num & 1; // Increment count if LSB is 1
num >>= 1; // Right shift by 1
}
}
return count;
}

// Optimized version using Brian Kernighan’s Algorithm
int countSetBitsOptimized(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
int num = i;
while (num) {
num = num & (num - 1); // Remove the rightmost set bit
count++;
}
}
return count;
}

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

cout << "Total set bits from 1 to " << n << " (simple method): "
<< countSetBits(n) << endl;

cout << "Total set bits from 1 to " << n << " (optimized method): "
<< countSetBitsOptimized(n) << endl;

return 0;
}