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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便