新增 n 個二進位制字串?


在此程式中,我們必須新增給定的二進位制數。有 n 個二進位制數,我們必須將它們全都相加,以輸出一個二進位制數。

為此,我們將使用二進位制加法邏輯,並逐個相加從 1 到 N 的所有項以得出結果。

Input: "1011", "10", "1001"
Output: 10110

解釋

更簡單的方法是將二進位制字串轉換為其十進位制等價形式,然後相加,再重新轉換為二進位制。在此,我們將手動進行加法。我們將使用一個幫助函式來新增兩個二進位制字串。該函式將針對 n 個不同的二進位制字串使用 n-1 次。

示例

#include<iostream>
using namespace std;
string add(string b1, string b2) {
   string res = "";
   int s = 0;
   int i = b1.length() - 1, j = b2.length() - 1;
   while (i >= 0 || j >= 0 || s == 1) {
      if(i >= 0) {
         s += b1[i] - '0';
      } else {
         s += 0;
      }
      if(j >= 0) {
         s += b2[j] - '0';
      } else {
         s += 0;
      }
      res = char(s % 2 + '0') + res;
      s /= 2;
      i--; j--;
   }
   return res;
}
string addbinary(string a[], int n) { string res = "";
   for (int i = 0; i < n; i++) {
      res = add(res, a[i]);
   }
   return res;
}
int main() {
   string arr[] = { "1011", "10", "1001" };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << addbinary(arr, n) << endl;
}

更新日期:20-Aug-2019

262 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始學習
廣告