 # Rightmost diff bit

I couldn’t get it what dose log(n &-n) will do in this code here is the link to the problem from geeks for geeks

here is code for the same

// C++ implementation to find the position
// of rightmost different bit
#include <bits/stdc++.h>
using namespace std;

// Function to find the position of
// rightmost set bit in ‘n’
int getRightMostSetBit(int n)
{
* return log2(n & -n) + 1;*   //here what is happening
}

// Function to find the position of
// rightmost different bit in the
// binary representations of ‘m’ and ‘n’
int posOfRightMostDiffBit(int m, int n)
{
// position of rightmost different
// bit
return getRightMostSetBit(m ^ n);
}

// Driver program
int main()
{
int m = 52, n = 4;
cout << posOfRightMostDiffBit(m, n);
return 0;
}

Basically it first takes 2’s complement of the given number and does a bitwise operation with the original number. This will give us the required set bit of the number and log2 will just given the position of that set bit.

An easier way to do the same is to use ffs function, which provides the same result.

1 Like

thank you