LeetCode 1318: Minimum Flips to Make a OR b Equal to c Solution

Master LeetCode problem 1318 (Minimum Flips to Make a OR b Equal to c), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1318. Minimum Flips to Make a OR b Equal to c

Problem Explanation

Explanation

To solve this problem, we can iterate through the bits of a, b, and c simultaneously. We can check if the corresponding bits in a and b are not equal to the corresponding bit in c. If not, we can increment the flips count accordingly. We can do this by performing bitwise operations to extract the least significant bits of a, b, and c.

Algorithm:

  1. Initialize a variable flips to 0.
  2. Iterate over the bits of a, b, and c simultaneously using a loop.
  3. Check if the least significant bit of a, b, and c are not equal to the bit in c.
  4. If not equal, increment the flips count.
  5. Right shift a, b, and c by 1 bit to move to the next bit.
  6. Repeat steps 3-5 until all bits are processed.
  7. Return the flips count as the minimum flips required.

Time Complexity: O(log n) where n is the maximum of a, b, and c. Space Complexity: O(1)

Solution Code

class Solution {
    public int minFlips(int a, int b, int c) {
        int flips = 0;
        while (a > 0 || b > 0 || c > 0) {
            int bitA = a & 1;
            int bitB = b & 1;
            int bitC = c & 1;
            if ((bitA | bitB) != bitC) {
                if (bitC == 0) {
                    flips += (bitA + bitB);
                } else {
                    flips += 1;
                }
            }
            a >>= 1;
            b >>= 1;
            c >>= 1;
        }
        return flips;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1318 (Minimum Flips to Make a OR b Equal to c)?

This page provides optimized solutions for LeetCode problem 1318 (Minimum Flips to Make a OR b Equal to c) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1318 (Minimum Flips to Make a OR b Equal to c)?

The time complexity for LeetCode 1318 (Minimum Flips to Make a OR b Equal to c) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1318 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1318 in Java, C++, or Python.

Back to LeetCode Solutions