यहां हम देखेंगे कि n बाइनरी संख्याओं को स्ट्रिंग के रूप में जोड़ने वाला प्रोग्राम कैसे लिखें। आसान तरीका है बाइनरी स्ट्रिंग को उसके दशमलव समतुल्य में बदलना, फिर उन्हें जोड़ना और वापस बाइनरी में बदलना। यहां हम मैन्युअली जोड़ करेंगे।
एल्गोरिदम
addTwoBinary(bin1, bin2)
begin
s := 0
result := खाली स्ट्रिंग
i := bin1 की लंबाई, j := bin2 की लंबाई
while i >= 0 OR j >= 0 OR s = 1, do
if i >= 0 then
s := s + bin1[i] को संख्या के रूप में
else
s := s + 0
end if
if j >= 0 then
s := s + bin2[j] को संख्या के रूप में
else
s := s + 0
end if
result := (s mod 2) को result के साथ जोड़ें
s := s / 2
i := i - 1
j := j - 1
done
return result
end
उदाहरण
#include <iostream>
using namespace std;
string addTwoBinary(string bin1, string bin2) {
string result = "";
int s = 0; // s बिट योग रखने के लिए
int i = bin1.length() - 1, j = bin2.length() - 1; // LSB से ट्रैवर्स करें
while (i >= 0 || j >= 0 || s == 1) {
if (i >= 0)
s += bin1[i] - '0';
else
s += 0;
if (j >= 0)
s += bin2[j] - '0';
else
s += 0;
result = char(s % 2 + '0') + result;
s /= 2; // कैरी प्राप्त करें
i--; j--;
}
return result;
}
string add_n_binary(string arr[], int n) {
string result = "";
for (int i = 0; i < n; i++)
result = addTwoBinary(result, arr[i]);
return result;
}
int main() {
string arr[] = {"1011", "10", "1001"};
int n = sizeof(arr) / sizeof(arr[0]);
cout << add_n_binary(arr, n) << endl;
return 0;
}
आउटपुट
10110