1. Bit-by-Bit Shift Scan
Intuition
While n > 0, check if the least significant bit is set using n & 1. If it is, increment count. Then right shift n >>= 1. Repeat until n becomes 0.
When to apply: Basic demonstration of binary representation traversal.
Algorithm
- Step 1: Set count = 0.
- Step 2: Loop while n > 0.
- Step 3: count += (n & 1).
- Step 4: n >>= 1.
- Step 5: Return count.
#include <iostream> using namespace std; int countSetBitsBrute(int n) { int count = 0; while (n > 0) { count += (n & 1); n >>= 1; } return count;} int main() { cout << "Brute (6): " << countSetBitsBrute(6) << endl; // 2 cout << "Brute (13): " << countSetBitsBrute(13) << endl; // 3 return 0;}Time & Space Complexity
- Time complexity:
O(log n) - Space complexity:
O(1)