From 04d7ec4fac2070fdbf6176b4394f22b3660e86ca Mon Sep 17 00:00:00 2001 From: SMRITI PRAJAPATI <143401846+Smriti-Prajapati@users.noreply.github.com> Date: Sat, 27 Sep 2025 21:51:08 +0530 Subject: [PATCH] Add count bit problem in bit manipulation --- bit_manipulation/count_bit.cpp | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 bit_manipulation/count_bit.cpp diff --git a/bit_manipulation/count_bit.cpp b/bit_manipulation/count_bit.cpp new file mode 100644 index 0000000..dbe3d5b --- /dev/null +++ b/bit_manipulation/count_bit.cpp @@ -0,0 +1,42 @@ +#include +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; +}