在 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.
最右侧的 set 位在这里位于索引 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP