Problem
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
Solution
First attempt : Time complexity O(n)
/**
* @param {number} n
* @param {number} k
* @return {number}
*/
var minChanges = function(n, k) {
if(n == k)
{
return 0;
}
let nbin = parseInt(n).toString(2).padStart(32,"0");
let kbin = parseInt(k).toString(2).padStart(32,"0");
let changes = 0;
for(let i = 0; i < nbin.length; i++){
if(nbin[i] != kbin[i] && nbin[i] == 1){
changes++;
}
else if(nbin[i] != kbin[i] && nbin[i] == 0){
return -1;
}
}
return changes;
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.