#include <iostream>
#include <stdio.h>
#include <vector>
#include <sstream>
using namespace std;
/*
问题:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
分析:题目是给定两个二进制字符串,求出两者的二进制和。
可以分别从两个字符串的最后一位遍历,然后逢2进1即可
输入:
11 1
10 1
10 10
输出:
100
11
100
关键:
1 首先对两个字符串逆置,然后从前向后累加,此时结果是逆序的,然后最后逆置,注意:如果有进位,需要输出进位
//补上进位,如果进位>0
if(carry > 0)
{
stream << carry;
}
*/
class Solution {
public:
string addBinary(string a, string b) {
//如果两个字符串都为空,返回空
if(a.empty() && b.empty())
{
return "";
}
//如果两个中有一个为空,就返回另一个
else if(a.empty())
{
return b;
}
else if(b.empty())
{
return a;
}
//接下来就是两个字符串都不为空,从后向前遍历
int lenA = a.length();
int lenB = b.length();
//遍历到有一方为空,后面直接拷贝
stringstream stream;
int i = 0 ;
char value1;
char value2;
int carry = 0;
int temp;
int result;
//必须是逆序的遍历,或者你提前把字符串变成最小位在字符串起始位置
reverse(a.begin() , a.end());
reverse(b.begin() , b.end());
while(i < lenA && i < lenB)
{
value1 = a.at(i);
value2 = b.at(i);
temp = (value1 - '0') + (value2 - '0') + carry;
result = temp % 2;
carry = temp / 2;
stream << result;
i++;
}
//到这里其中一个字符串为空了,将后续a中剩余字符和carry一起处理
while(i < lenA)
{
value1 = a.at(i);
temp = (value1 - '0') + carry;
result = temp % 2;
carry = temp / 2;
stream << result;
i++;
}
while(i < lenB)
{
value2 = b.at(i);
temp = (value2 - '0') + carry;
result = temp % 2;
carry = temp / 2;
stream << result;
i++;
}
//补上进位,如果进位>0
if(carry > 0)
{
stream << carry;
}
//stream存储的结果是逆序的
string realResult = stream.str();
reverse(realResult.begin() , realResult.end());
//逆置后找到第一个非0字符
//int pos = realResult.find_first_not_of('0');
//realResult = realResult.substr(pos);
return realResult;
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
Solution solution;
string strA;
string strB;
string result;
while(cin >> strA >> strB )
{
result = solution.addBinary(strA , strB);
cout << result << endl;
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:67. Add Binary
最新推荐文章于 2023-02-07 10:25:41 发布