使用 C++ 中的位來新增兩個無符號數字。


表示為位流的無符號數字以二進位制形式寫出。

54 的二進位制形式是 110110。

使用位來新增兩個數字,我們將使用二進位制加法邏輯來新增其二進位制形式。

位加法的規則是 −

  • 0+0 = 0
  • 1+0 = 1
  • 0+1 = 1
  • 1+1 = 0 加 1

我們舉個例子來新增兩個數字,

Input: a = 21 (10101) , b = 27 (11011)
Output: 48 (110000)

說明 − 10101 + 11011 = 110000。我們將從最小有效位開始新增位。然後傳播到下個位。

示例

#include <bits/stdc++.h>
#define M 32
using namespace std;
int binAdd (bitset < M > atemp, bitset < M > btemp){
   bitset < M > ctemp;
   for (int i = 0; i < M; i++)
      ctemp[i] = 0;
   int carry = 0;
   for (int i = 0; i < M; i++) {
      if (atemp[i] + btemp[i] == 0){
         if (carry == 0)
            ctemp[i] = 0;
         Else {
            ctemp[i] = 1;
            carry = 0;
         }
      }
      else if (atemp[i] + btemp[i] == 1){
         if (carry == 0)
            ctemp[i] = 1;
         else{
            ctemp[i] = 0;
         }
      }
      else{
         if (carry == 0){
            ctemp[i] = 0;
            carry = 1;
         }
         else{
            ctemp[i] = 1;
         }
      }
   }
   return ctemp.to_ulong ();
}
int main () {
   int a = 678, b = 436;
   cout << "The sum of " << a << " and " << b << " is ";
   bitset < M > num1 (a);
   bitset < M > num2 (b);
   cout << binAdd (num1, num2) << endl;
}

輸出

The sum of 678 and 436 is 1114

更新時間:2019 年 9 月 19 日

599 次瀏覽

開啟你的職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.