兩個二進位制數之和中最右側位產生第一個進位位的座標


在本問題中,給出兩個正整數 N 和 M。我們的任務是打印出二進位制中 N 和 M 求和時生成第一個進位位的最右側位。

舉個例子來理解問題,

輸入 − N = 5,M = 14

輸出 − 3

說明

(5)2 = 0101 , (14)2 = 1110
Sum 0101
+   1110
    10011

要解決這個問題,我們來考慮一下布林代數的一些觀察。

當兩個數字都是 1 時,求和將會產生進位。所以,我們要找出所有產生進位的位。這可以透過查詢兩個數字的與運算來完成。並且找到該數字的最右側位。

這看起來有點難以理解,讓我們用這種方法解決一個例子。

N = 5 and M = 14
N&M = 0100

這裡最右側的設定位在索引 3 處。

示例

程式展示了我們解決方案的實現,

 即時演示

#include <iostream>
#include <math.h>
using namespace std;
int rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   return bitIndex;
}
void rightCarryBit(int N, int M) {
   int carryIndex = rightSetBit(N & M);
   cout<<carryIndex;
}
int main() {
   int N=4, M=14;
   cout<<"The position of rightmost bit that generates carry in the sum of "<<N<<" and "<<M<<" is ";
   rightCarryBit(N,M);
   return 0;
}

輸出

The position of rightmost bit that generates carry in the sum of 4 and 14 is 3

更新時間: 2020-4-17

82 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.