容易 二进制求和
22
%
通过
给定两个二进制字符串,返回他们的和(用二进制表示)。
您在真实的面试中是否遇到过这个题?
Yes
样例
标签 Expand
a = 11
b = 1
返回 100
#include <iostream>
using namespace std;
class Solution {
public:
/**
* @param a a number
* @param b a number
* @return the result
*/
string addBinary(string& a, string& b) {
// Write your code here
string res;
int len = a.size() > b.size()? a.size(): b.size();
int la = a.size();
int lb = b.size();
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int carry = 0;
for(int i = 0; i < len; i++) {
int x = i < la? a[i]-'0': 0;
int y = i < lb? b[i]-'0': 0;
int v = (x+y+carry)%2;
carry = (x+y+carry)/2;
res.insert(res.begin(), v+'0');
}
if(carry == 1)
res.insert(res.begin(), '1');
return res;
}
};