1. Popcount followed by Linear Scan
Intuition
If n <= 0, return -1. Count set bits by checking n & 1 and shifting right. If total set bits is not equal to 1, return -1. Otherwise, run a second loop to find which position held the 1.
When to apply: Basic demonstration of independent verification and scanning.
Algorithm
- Step 1: If n <= 0, return -1.
- Step 2: Count bits in n. If count != 1, return -1.
- Step 3: Scan bit positions 1 to 32: return position where bit is set.
#include <iostream> using namespace std; int findPositionBrute(int n) { if (n <= 0) return -1; int count = 0; int temp = n; while (temp > 0) { count += (temp & 1); temp >>= 1; } if (count != 1) return -1; int pos = 1; while ((n & 1) == 0) { n >>= 1; pos++; } return pos;} int main() { cout << "Brute (16): " << findPositionBrute(16) << endl; // 5 cout << "Brute (12): " << findPositionBrute(12) << endl; // -1 cout << "Brute (0): " << findPositionBrute(0) << endl; // -1 return 0;}Time & Space Complexity
- Time complexity:
O(log n) - Space complexity:
O(1)