leetcode[67]Add Binary

4546 ワード

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 lena=a.size();

    int lenb=b.size();

    if (lena==0)return b;

    if (lenb==0)return a;

    string c="";

    int flag=0;

    while(lena>0&&lenb>0)

    {

        int temp=a[lena-1]-'0'+b[lenb-1]-'0'+flag;

        c=char(temp%2+'0')+c;

        flag=temp/2;

        lena--;

        lenb--;

    }

    while(lena>0)

    {

        int temp=a[lena-1]-'0'+flag;

        c=char(temp%2+'0')+c;

        flag=temp/2;

        lena--;

    }

    while(lenb>0)

    {

        int temp=b[lenb-1]-'0'+flag;

        c=char(temp%2+'0')+c;

        flag=temp/2;

        lenb--;

    }

    if(flag>0)c=char(flag+'0')+c;

    return c;

}

};