用 C++ 编写程序将两个二进制字符串相加,并返回二进制字符串
pythonserver side programmingprogramming更新于 2026/1/8 23:40:17
假设我们有两个二进制字符串 a 和 b,我们必须将这些二进制数相加并求出它们的和,同样以字符串形式返回。
因此,如果输入为 a = "10110", b = "10010",则输出为 "101000"。
要解决这个问题,我们将遵循以下步骤 −
- ret := 空字符串
- na := a 的大小,nb := b 的大小
- i := na - 1, j := nb - 1
- carry := 0
- while (i >= 0 or j >= 0),执行:
- addA := (如果 i >= 0,则 a[i] - ASCII 为 '0',否则为 0)
- addB := (如果 j >= 0,则 b[j] - ASCII 为 '0',否则为 0)
- sum := addA + addB + carry
- carry := sum / 2
- sum := sum mod 2
- ret := ret 连接 sum
- (将 i 减少 1)
- (将 j 减少 1)
- 如果 carry 非零,则:
- ret := ret 连接进位
- 反转数组 ret
- 返回 ret
让我们看看下面的实现以便更好地理解 −
示例
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string solve(string a, string b){
string ret = "";
int na = a.size();
int nb = b.size();
int i = na - 1;
int j = nb - 1;
int carry = 0;
while(i >= 0 || j >= 0){
int addA = i >= 0 ? a[i] - '0' : 0;
int addB = j >= 0 ? b[j] - '0' : 0;
int sum = addA + addB + carry;
carry = sum / 2;
sum %= 2;
ret += to_string(sum);
i--;
j--;
}
if(carry)
ret += to_string(carry); reverse(ret.begin(), ret.end());
return ret;
}
};
main(){
string a = "10110", b = "10010"; Solution ob;
cout << ob.solve(a, b);
}
输入
"10110","10010"
输出
101000
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

