Wednesday, January 15, 2025

Minimum Bit Flips to Convert Number

Programming LanguageMinimum Bit Flips to Convert Number


Problem

We have to find out how many bits are needed to be flipped in start to make it equal to goal
We know that exor produces 1 for odd number of 1 else 0
This can help us in identifying how many bits are needed to be flipped in start to make it equal to goal

TC:


O(log2X)O(log_{2}X)

class Solution {
    public int minBitFlips(int start, int goal) {
        int exorVal  = start ^ goal;

        StringBuilder str = new StringBuilder();
        int count = 0;

//logarithmic time complexity
        while(exorVal!=0){
            if(exorVal%2 ==1) count++;
            exorVal = exorVal/2;
        }
        return count;
    }
}
Enter fullscreen mode

Exit fullscreen mode

Check out our other content

Check out other tags:

Most Popular Articles