添加 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;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP