Problem Description
Given three positive integers a, b, and c, determine the minimum number of bit flips required on a and b so that the bitwise OR (a OR b) equals c. A single flip changes a 0 to a 1 or a 1 to a 0 in the binary representation.
Key Insights
- For each bit position, extract the corresponding bits from a, b, and c.
- If the target bit in c is 0, both bits in a and b must be 0; any 1's must be flipped.
- If the target bit in c is 1, at least one of a or b must be 1; if both are 0, one flip is required.
- Iterate through all 32 bits (since a, b, and c can be as large as 10^9) to compute the total flips.
Space and Time Complexity
Time Complexity: O(1) – We process a constant 32 bits regardless of the input values. Space Complexity: O(1) – Only a fixed amount of extra space is used.
Solution
The solution iterates over each bit position (0 through 31) and examines the bits of a, b, and c:
- Extract the bit at the current position for a, b, and c.
- If the bit in c is 0, then any 1s in a or b at that position are extra and need to be flipped.
- If the bit in c is 1, then if both a and b have 0 at that bit position, one flip is needed to make it 1.
- Sum the flips required for each bit position.
This bit-by-bit approach ensures that we only flip the necessary bits and correctly account for cases where both bits contribute to the discrepancy.