Minimize XOR

Problem 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

Jan 16, 2025 - 07:13
Minimize XOR

Problem

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;
    }

}