首页 > 代码库 > Leetcode_Add Binary

Leetcode_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) {
                size_t  na = a.size();
        int  nb = b.size();
        int n = na > nb ? na : nb;
        
        string result(n,'0');
        int  ch= 0;
        int i= n-1,ia=na-1,ib=nb-1;
        for(;ia >=0 && ib >= 0; ){
            int re = a[ia]-'0'+b[ib]-'0' + ch;
            ch=re/2;
            result[i]=re%2+'0';
            ia--;
            ib--;
            i--;
        }
        //int re  = a[0]+b[0]-'0'+'0'+ch;
        while(ia >=0){
           int re = a[ia]-'0' +ch;
           ch = re/2;
           result[i] = re%2+'0';
           ia--;
           i--;

        }
        
        while(ib >=0){
            int re = b[ib]-'0'+ch;
            ch = re/2;
            ib--;
            result[i]= re%2+'0';

            i--;
        }
      
        if(ch){
            result.insert(0,"1");
        }
      
        return result;
    }
};