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

更新時間: 2020 年 4 月 17 日

156 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.