1. Linear Bit Scan
Intuition
If n == 0, return 0. Initialize pos = 1. In a while loop, test if (n & 1) == 1. If yes, return pos. Otherwise, shift n >>= 1 and increment pos.
When to apply: Basic simulation.
Algorithm
- Step 1: If n == 0, return 0.
- Step 2: Initialize pos = 1.
- Step 3: While (n & 1) == 0: n >>= 1, pos++.
- Step 4: Return pos.
#include <iostream> using namespace std; int getFirstSetBitPosBrute(int n) { if (n == 0) return 0; int pos = 1; while ((n & 1) == 0) { n >>= 1; pos++; } return pos;} int main() { cout << "Brute (18): " << getFirstSetBitPosBrute(18) << endl; // 2 cout << "Brute (19): " << getFirstSetBitPosBrute(19) << endl; // 1 cout << "Brute (0): " << getFirstSetBitPosBrute(0) << endl; // 0 return 0;}Time & Space Complexity
- Time complexity:
O(log n) - Space complexity:
O(1)