1. 32-Bit Fixed Position Check
Intuition
Initialize count = 0. Loop i from 0 to 31. If (n >> i) & 1 == 1, increment count.
When to apply: Baseline comparison.
Algorithm
- Step 1: Initialize count = 0.
- Step 2: Loop i from 0 to 31.
- Step 3: If ((n >> i) & 1) != 0, count++.
- Step 4: Return count.
#include <iostream> using namespace std; int hammingWeightBrute(uint32_t n) { int count = 0; for (int i = 0; i < 32; ++i) { if ((n >> i) & 1) count++; } return count;} int main() { cout << "Brute (11): " << hammingWeightBrute(11) << endl; // 3 cout << "Brute (128): " << hammingWeightBrute(128) << endl; // 1 return 0;}Time & Space Complexity
- Time complexity:
O(32) = O(1) - Space complexity:
O(1)