Add Binary

来源:互联网 发布:美国极进网络 编辑:程序博客网 时间:2024/05/29 02:47

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

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

比较简单,注意进位即可:

string addBinary(string a, string b){    string ans;    int bLength = b.length(), aLength = a.length();    int newLength = max(aLength, bLength);    int temp = 0;    for (int i = 0; i <newLength; i++)    {        if (aLength > 0)            temp += a[aLength-1] - '0';        if (bLength > 0)            temp += b[bLength-1] - '0';        if(temp==0)        {            ans = '0' + ans;            temp=0;        }        else if(temp==1)        {            ans = '1' + ans;            temp=0;        }        else if(temp==2)        {            ans = '0' + ans;            temp=1;        }        else if(temp==3)        {            ans = '1' + ans;            temp=1;        }        aLength--;        bLength--;    }    if (temp > 0)        ans = '1' + ans;    return ans;}

再简单点可以用移位:

string addBinary(string a, string b) {    string ans;    int bLength = b.length(), aLength = a.length();    int newLength = max(aLength, bLength);    int temp = 0;    for (int i = 0; i <newLength; i++)    {        if (aLength > 0)        {            temp += a[aLength-1] - '0';        }        if (bLength > 0)        {            temp += b[bLength-1] - '0';        }        ans = (char) ((temp & 1) + '0') + ans;        temp = temp >> 1;        aLength--;        bLength--;    }    if (temp > 0)        ans = '1' + ans;    return ans;    }





0 0