leetcode_question_67 Add Binary

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

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

 

bool isAllZero(string a)
{
    for (int i = 0; i < a.length(); ++i) {
        if (a[i] != '0')return false;
    }
    return true;
}
string stringxor(string a, string b) {
    string res="";
    int al = a.length()-1;
    int bl = b.length()-1;
    for (;al >=0 && bl >= 0; al--,bl--) {
        char tmp = '0' + (a[al]-'0')^(b[bl]-'0');
        res = tmp + res;
    }
    if (al >= 0) res = a.substr(0,al+1) + res;
    if (bl >= 0) res = b.substr(0,bl+1) + res;
    return res;
}

string stringand(string a, string b) {
    string res="";
    int al = a.length()-1;
    int bl = b.length()-1;
    for (;al >=0 && bl >= 0; al--,bl--) {
        char tmp = '0' + ((a[al]-'0')&(b[bl]-'0'));
        res = tmp + res;
    }
    return res;
}

string addBinary(string a, string b) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (a == "") return b;
    if (b == "") return a;

    string xorres = "";
    string andres = "";
    do {
        xorres = stringxor(a,b);
        andres = stringand(a,b);
        andres += '0';
        a = xorres;
        b = andres;
    } while (!isAllZero(b));

    int i = 0;
    for (; i < a.length(); ++i)
        if (a[i] != '0') break;
    if (i >= a.length())
        a = "0";
    else
        a = a.substr(i);
    return a;

}


 

 

posted @ 2013-09-15 20:39  pangbangb  阅读(151)  评论(0编辑  收藏  举报