在 C++ 中添加 n 个二进制字符串?
我们将在本文中展示如何编写一个程序,该程序可以添加 n 个给定为字符串的二进制数字。更简单的方法是将二进制字符串转换为其十进制等价形式,然后相加并再次转换为二进制形式。本文中,我们将手动执行加法。
我们将使用一个辅助函数来添加两个二进制字符串。该函数将被用于 n-1 次的不同 n 个二进制字符串。该函数的工作方式如下。
算法
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP