2진수가 있는 두 개의 문자열이 주어지면 이 두 개의 이진 문자열을 더한 결과를 찾고 결과를 이진 문자열로 반환해야 합니다.
2진수는 0 또는 1로 표현되는 숫자입니다. 2개의 2진수를 더할 때 주의해야 할 이진수 덧셈 규칙이 있습니다.
0+0 → 0 0+1 → 1 1+0 → 1 1+1 → 0, carry 1

입력
str1 = {“11”}, str2 = {“1”} 출력
“100”
입력
str1 = {“110”}, str2 = {“1”} 출력
“111”
문제를 해결하기 위해 다음과 같은 접근 방식을 사용합니다.
-
마지막에서 두 문자열 모두 순회
-
두 숫자의 이진수 더하기
-
1이 두 개 있으면 0으로 만들고 1을 나릅니다.
-
결과를 반환합니다.
알고리즘
Start Step 1→ declare function to add two strings string add(string a, string b) set string result = "" set int temp = 0 set int size_a = a.size() – 1 set int size_b = b.size() – 1 While (size_a >= 0 || size_b >= 0 || temp == 1) Set temp += ((size_a >= 0)? a[size_a] - '0': 0) Set temp += ((size_b >= 0)? b[size_b] - '0': 0) Calculate result = char(temp % 2 + '0') + result Set temp /= 2 Set size_a— Set size_b— End return result Step 2→ In main() Declare string a = "10101", b="11100" Call add(a, b) Stop호출
예시
#include<bits/stdc++.h>
using namespace std;
//function to add two strings
string add(string a, string b){
string result = "";
int temp = 0;
int size_a = a.size() - 1;
int size_b = b.size() - 1;
while (size_a >= 0 || size_b >= 0 || temp == 1){
temp += ((size_a >= 0)? a[size_a] - '0': 0);
temp += ((size_b >= 0)? b[size_b] - '0': 0);
result = char(temp % 2 + '0') + result;
temp /= 2;
size_a--; size_b--;
}
return result;
}
int main(){
string a = "10101", b="11100";
cout<<"sum of strings are : "<<add(a, b);
return 0;
} 출력
위의 코드를 실행하면 다음 출력이 생성됩니다 -
sum of strings are : 110001