DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Minimum 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) Where X is (start exor end)
SC: O(1)

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

Top comments (0)