1. 32-Bit Fixed Loop Inspection
Intuition
Loop i from 0 to 31. Extract ba = (a >> i) & 1, bb = (b >> i) & 1, bc = (c >> i) & 1. If bc == 0, add ba + bb. If bc == 1 and ba == 0 && bb == 0, add 1.
When to apply: Basic baseline.
Algorithm
- Step 1: Set flips = 0.
- Step 2: Loop i from 0 to 31.
- Step 3: Extract ba = (a >> i) & 1, bb = (b >> i) & 1, bc = (c >> i) & 1.
- Step 4: If bc == 0: flips += ba + bb.
- Step 5: Else if ba == 0 && bb == 0: flips += 1.
- Step 6: Return flips.
#include <iostream> using namespace std; int minFlipsBrute(int a, int b, int c) { int flips = 0; for (int i = 0; i < 32; ++i) { int ba = (a >> i) & 1; int bb = (b >> i) & 1; int bc = (c >> i) & 1; if (bc == 0) { flips += ba + bb; } else { if (ba == 0 && bb == 0) flips += 1; } } return flips;} int main() { cout << "Brute (2, 6, 5): " << minFlipsBrute(2, 6, 5) << endl; // 3 cout << "Brute (4, 2, 7): " << minFlipsBrute(4, 2, 7) << endl; // 1 return 0;}Time & Space Complexity
- Time complexity:
O(32) = O(1) - Space complexity:
O(1)