C ++中最右边不同位的位置
在这个问题中,我们给了两个数字N和M。我们的任务是在数字的二进制表示形式中找到最右边的不同位的索引。
让我们举个例子来了解这个问题,
输入-N=12,M=9
输出 -2
说明 -(12)2=1100和(10)2=1010。
右数第二位是另一位。
为了解决这个问题,我们将必须找到数字的所有不同位。要找到所有不同的位,我们将找到M和N的异或。然后,我们将找到M^N的最右边的位。
理解起来似乎有点复杂,让我们使用这种方法来解决一个例子。
N = 12 , M = 9 N^M = 0110.
此处最右边的设置位在索引2处。
示例
展示我们解决方案实施情况的程序,
#include <iostream>
#include <math.h>
using namespace std;
int rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   return bitIndex;
}
void rightDiffBit(int m, int n) {
   int diffBit = rightSetBit(m^n);
   cout<<diffBit;
}
int main() {
   int N = 12, M = 10;
   cout<<"Postion of first right different bit of the number "<<N<<" & "<<M<<" is ";
   rightDiffBit(N, M);
   return 0;
}输出结果
Postion of first right different bit of the number 12 & 10 is 2