Depend of matching set and unset bits in given integers

[ad_1]

Two integers X and Y are the duty is to seek out the variety of bits which can be similar of their binary illustration by not contemplating any main zeroes after the leftmost set little bit of the higher quantity in binary type.

Examples:

Enter:  X = 10, Y = 6
Output:  2
Rationalization: The binary illustration of 10 is 1010 and 6 is 0110. So, the variety of similar bits are 2.

Enter : X = 3, Y = 16
Output : 2

 

Method: 

Instinct:

Calculate least vital bit (LSB) through the use of (i % 2), the place i is any integer and Examine if the least vital bit (LSB) of the given integer X, Y are similar or not. If similar then, increment the reply and proper shift the each integer by 1 for checking the LSB are similar or not for subsequent bit.

Algorithm:

  • Hold doing the next steps till both X or Y just isn’t 0.
    • Calculate LSB of given integer X and Y by X % 2 and Y % 2 and verify if each are similar or not.
      • If similar, then increment the reply
    • Proper shift the each given integer by 1

Beneath is the implementation of the above method:

C++

#embody <bits/stdc++.h>

utilizing namespace std;

  

int remedy(int X, int Y)

{

    int ans = 0;

  

    whereas (X != 0 || Y != 0) {

        

        if (X % 2 == Y % 2)

            ans++;

  

        

        X >>= 1;

        Y >>= 1;

    }

  

    return ans;

}

  

int essential()

{

    int X = 10, Y = 6;

  

    

    cout << remedy(X, Y);

  

    return 0;

}

Time Complexity: O(1)
Auxiliary House: O(1)

[ad_2]

Leave a Reply