dev-resources.site
for different kinds of informations.
Minimize XOR
Published at
1/16/2025
Categories
leetcode
bitmanipulation
dsa
Author
Prashant Mishra
Main Article
TC : (n+m) where n and m are no. of bits in num1 and num2 respectively
/*
use cases
check if ith bit is set or not
toggle ith bit
count of bits in a number
*/
class Solution {
public int minimizeXor(int num1, int num2) {
int c1 = count(num1);
int c2 = count(num2);
int number = num1;
if(c1> c2){
int i = 0;
while(c1!=c2){
//keep on resetting the least significant bits from right to help till c1 == c2
//check if ith bit is set then unset it and decrement count
if((number & (1<<i))!=0){
number = number ^ (1<<i);// toggle the ith bit
c1 = c1-1;
}
i++;
}
}
else if (c1 < c2) {
int i = 0;
while(c1!=c2){
//check if the ith bit is 0
if((number & (1<<i))==0){
number = number ^ ( 1<<i); //toggle that bit
c1+=1;
}
i++;
}
}
return number;
}
//count no. of set bits in n
public int count(int n){
int count = 0;
while(n!=0){
count+=(1&n);
n = n>>1;
}
return count;
}
}
Articles
12 articles in total
Minimize XOR
currently reading
Count prefix and suffix I and II
read article
Rabin Karp (hashing) String pattern matching
read article
Min no. of operations to move all balls to each box
read article
Find all anagrams in the string[Fixed Window pattern]
read article
No of ways to split Array
read article
Range sum query 2D - Immutable
read article
Count vowel strings in ranges
read article
Range Sum Query - Immutable
read article
Job Scheduling Problem with Max Profit
read article
Non overlapping intervals
read article
Minimum No. of arrows to burst balloons
read article
Featured ones: