1. 程式人生 > >Add Binary 二進位制加法

Add Binary 二進位制加法

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 len1,len2,t,i;
        string res;
        len1=a.length()-1;
        len2=b.length()-1;
        t=0;
        while(len1>=0&&len2>=0)
        {
            t=(a[len1]-'0')+(b[len2]-'0')+t;
            res=char(t%2+'0')+res;
            t/=2;
            len1--;
            len2--;
        }
        while(len1>=0)
        {
            t=a[len1]-'0'+t;
            res=char(t%2+'0')+res;
            t/=2;
            len1--;
        }
        while(len2>=0)
        {
            t=b[len2]-'0'+t;
            res=char(t%2+'0')+res;
            t/=2;
            len2--;
        }
        if(t>0)
        {
            res=char(t+'0')+res;
        }
        return res;
    }
};