C ++中两个数字中最右边的公共位的位置

在这个问题中,我们给了两个数字M和N。我们的任务是打印两个数字中最右边的公共位的位置(索引)。

让我们举个例子来了解这个问题,

输入-N = 4,M = 7

输出-3

说明-(4)2 = 100,(7)2 =111。最右边的公共位在索引3处。

为了解决这个问题,我们将必须找到数字的所有相同位。要找到所有相同的位,我们将找到M和N的异或。然后,我们将在M ^ N的求反中找到最右边的位。

理解起来似乎有点复杂,让我们使用这种方法来解决一个例子。

N = 4 , M = 7
~N^M = 100.

此处最右边的设置位在索引3处。

示例

显示我们解决方案实施情况的程序,

#include <iostream>
#include <math.h>
using namespace std;
int rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   return bitIndex;
}
void rightSameBit(int m, int n) {
   int diffBit = rightSetBit(~(m^n));
   cout<<diffBit;
}
int main() {
   int N = 4, M = 7;
   cout<<"Postiion of first right same bit of the number "<<N<<" & "<<M<<" is ";
   rightSameBit(N, M);
   return 0;
}

输出结果

Postiion of first right same bit of the number 4 & 7 is 3