Posts Bit Difference (geeksforgeeks - SDE Sheet)
Post
Cancel

Bit Difference (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

You are given two numbers A and B. The task is to count the number of bits needed to be flipped to convert A to B.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {

    public static int countBitsFlip(int a, int b) {

        // XOR of A and B will give a number where the bits set to '1' represent
        // positions where A and B have different bits.
        int n = a ^ b;

        int count = 0;

        // Loop through each bit of n
        while(n != 0) {

            // Check if the least significant bit (rightmost bit) is set to '1'
            // If so, it means the corresponding bits of A and B differ at that position
            if( (n & 1) != 0 ) {
                count++;
            }

            // Right shift n by 1 to check the next bit in the next iteration
            n = n >> 1;
        }

        return count;
    }
}
This post is licensed under CC BY 4.0 by the author.