Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution { public: string addBinary(string a, string b) { int carry = 0, alen = a.length(),blen = b.length(); string res=""; if(alen > blen) {b=string(alen-blen,‘0‘)+b;blen = alen;} if(alen < blen) {a=string(blen-alen,‘0‘)+a;alen = blen;} for(int i = alen-1; i>=0 ; -- i){ int num =(a[i]-‘0‘)+(b[i]-‘0‘)+carry; carry = 0; if(num >= 2) {num-=2;carry=1;} res+=‘0‘+num; } if(carry) res+=‘1‘; reverse(res.begin(),res.end()); return res; } };
Leetcode Add Binary,布布扣,bubuko.com
原文:http://www.cnblogs.com/xiongqiangcs/p/3808949.html