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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP