給定兩個二進制字符串,返回他們的和(用二進制表示)。
輸入爲非空字符串且只包含數字 1
和0
。
示例 1:
輸入: a = “11”, b = “1”
輸出: “100”
示例 2:
輸入: a = “1010”, b = “1011”
輸出: “10101”
我的代碼:
class Solution {
public:
string addBinary(string a, string b) {
string res,tmp;
int j=0;
for(int i=0;i<abs(int(a.length()-b.length()));i++)
tmp.append("0");
if(a.length()>b.length()) b = tmp+b;
else a=tmp+a;
for(int i=a.length()-1;i>=0;i--)
{
int a1 = a.at(i) - '0';
int b1 = b.at(i) - '0';
if(a1+b1+j>=2){
res.append(judge(a1+b1+j-2));
j=1;
}
else{
res.append(max(judge(a1+j),judge(b1+j)));
j=0;
}
}
if(j==1) res.append("1");
reverse(res.begin(),res.end());
return res;
}
string judge(int s){
if(s==0) return "0";
else if(s==1) return "1";
}
};
大佬的代碼:
string addBinary(string a, string b)
{
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}