在 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 處。

示例

程式展示瞭解決方案的實現情況,

 Live Demo

#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

更新時間: 17-Apr-2020

已 瀏覽 314 次

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.