首页 > 代码库 > Add Binary

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路简单(同Add Two Numbers),可从代码得知,需要注意字符在字符串中的插入;

code:

class Solution {public:    string addBinary(string a, string b) {        string result;        reverse(a.begin(),a.end());        reverse(b.begin(),b.end());                int maxlength=max(a.size(),b.size());        int carry=0;                for(int i=0;i<maxlength;++i)        {            int ai=i<a.size() ? a[i]-0:0;            int bi=i<b.size() ? b[i]-0:0;                        int sum=ai+bi+carry;            result.insert(result.begin(),sum%2+0);            carry=sum/2;        }                if(carry==1)            result.insert(result.begin(),1);        return result;    }};
View Code

 

Add Binary