LeetCode 3226: Number of Bit Changes to Make Two Integers Equal Solution

Master LeetCode problem 3226 (Number of Bit Changes to Make Two Integers Equal), a easy 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.

3226. Number of Bit Changes to Make Two Integers Equal

Problem Explanation

Explanation

To solve this problem, we need to compare the binary representations of integers n and k. We iterate through the bits of n and k simultaneously. If a bit in n is 1 and the corresponding bit in k is 0, we need to change that bit. We can count the number of changes needed and return it as the result. If at any point we encounter a situation where n has more 1s than k, it is impossible to make n equal to k and we return -1.

  • Time complexity: O(log(max(n, k)))
  • Space complexity: O(1)

Solution Code

class Solution {
    public int minFlips(int n, int k) {
        int count = 0;
        while (n > 0 || k > 0) {
            if ((n & 1) == 1 && (k & 1) == 0) {
                count++;
            }
            n >>= 1;
            k >>= 1;
        }
        return (n > 0) ? -1 : count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3226 (Number of Bit Changes to Make Two Integers Equal)?

This page provides optimized solutions for LeetCode problem 3226 (Number of Bit Changes to Make Two Integers Equal) 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 3226 (Number of Bit Changes to Make Two Integers Equal)?

The time complexity for LeetCode 3226 (Number of Bit Changes to Make Two Integers Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3226 on DevExCode?

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

Back to LeetCode Solutions