在C++中添加两个二进制字符串的程序
给定两个二进制数字字符串,我们需要找到通过将这两个二进制字符串相加而得到的结果并返回结果作为二进制字符串。
二进制数是指表示为0或1的数字。在添加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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP