여기서 우리는 문자열로 주어진 n개의 이진수를 더할 수 있는 프로그램을 작성하는 방법을 볼 것입니다. 더 쉬운 방법은 이진 문자열을 해당하는 십진수로 변환한 다음 추가하고 다시 이진으로 변환하는 것입니다. 여기서는 수동으로 추가를 수행합니다.
하나의 도우미 함수를 사용하여 두 개의 이진 문자열을 추가합니다. 이 함수는 n개의 다른 이진 문자열에 대해 n-1번 사용됩니다. 기능은 다음과 같이 작동합니다.
알고리즘
addTwoBinary(bin1, bin2)
begin s := 0 result is an empty string now i := length of bin1, and j := length of bin2 while i >= 0 OR j>=0 OR s is 1, do if i >=0 then, s := s + bin1[i] as number else s := s + 0 end if if j >=0 then, s := s + bin2[j] as number else s := s + 0 end if result := (s mod 2) concatenate this with result itself 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 will be used to hold bit sum
int i = bin1.length() - 1, j = bin2.length() - 1; //traverse from 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; //get the carry
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;
}
main() {
string arr[] = { "1011", "10", "1001" };
int n = sizeof(arr) / sizeof(arr[0]);
cout << add_n_binary(arr, n) << endl;
} 출력
10110