Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:反转在逐位加,在反
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using std::vector;
using std::string;
using std::cout;
class Solution {
string addbinary(string &less,string &b)
{
string temp;
if (less.size() > b.size())
swap(less,b);
char c = 0;//进位
char n;
size_t len = b.size();
size_t less_len = less.size();
for (int i =0;i!=len;++i){
if (i < less_len){
if ((less[i] + b[i] + c -48) >= '2'){
temp.push_back((less[i] + b[i] + c -48) - 2);
c = 1;
}else{
temp.push_back((less[i] + b[i] +c - 48));
c = 0;
}
}else{
temp.push_back(b[i]+c -48 == 2?48:b[i]+c);
c = b[i] + c -48 == 2?1:0;
}
}
if (c == 1){
temp.push_back(49);
}
return temp;
}
public:
string addBinary(string a, string b) {
string temp;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
temp = addbinary(a,b);
reverse(temp.begin(),temp.end());
return temp;
}
};
int main()
{
Solution sol;
cout << sol.addBinary("11","11");
}