3226. Number of Bit Changes to Make Two Integers Equal LeetCode Solution
In this guide, you will get 3226. Number of Bit Changes to Make Two Integers Equal LeetCode Solution with the best time and space complexity. The solution to Number of Bit Changes to Make Two Integers Equal problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Number of Bit Changes to Make Two Integers Equal solution in C++
- Number of Bit Changes to Make Two Integers Equal solution in Java
- Number of Bit Changes to Make Two Integers Equal solution in Python
- Additional Resources

Problem Statement of Number of Bit Changes to Make Two Integers Equal
You are given two positive integers n and k.
You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
Return the number of changes needed to make n equal to k. If it is impossible, return -1.
Example 1:
Input: n = 13, k = 4
Output: 2
Explanation:
Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.
Example 2:
Input: n = 21, k = 21
Output: 0
Explanation:
n and k are already equal, so no changes are needed.
Example 3:
Input: n = 14, k = 13
Output: -1
Explanation:
It is not possible to make n equal to k.
Constraints:
1 <= n, k <= 106
Complexity Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
3226. Number of Bit Changes to Make Two Integers Equal LeetCode Solution in C++
class Solution {
public:
int minChanges(unsigned n, unsigned k) {
// n needs to be a superset of k.
return (n & k) == k ? popcount(n ^ k) : -1;
}
};
/* code provided by PROGIEZ */
3226. Number of Bit Changes to Make Two Integers Equal LeetCode Solution in Java
class Solution {
public int minChanges(int n, int k) {
// n needs to be a superset of k.
return (n & k) == k ? Integer.bitCount(n ^ k) : -1;
}
}
// code provided by PROGIEZ
3226. Number of Bit Changes to Make Two Integers Equal LeetCode Solution in Python
class Solution:
def minChanges(self, n: int, k: int) -> int:
# n needs to be a superset of k.
return (n ^ k).bit_count() if (n & k) == k else -1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.