关闭

leetcode 66:Add Binary

111人阅读 评论(0) 收藏 举报
分类:

题目:

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 result = "";
    int apos = a.size() - 1;
    int bpos = b.size() - 1;
    int adigit, bdigit, carry = 0;

    while (apos >= 0 || bpos >= 0 || carry == 1)
    {
        adigit = bdigit = 0;

        if (apos >= 0) adigit = a[apos--] == '1';
        if (bpos >= 0) bdigit = b[bpos--] == '1';

        // Another way: the digit is 1 if adigit + bdigit + carry == 1 or == 3, but I noticed that
        // XOR is more concise:
        result = static_cast<char>(adigit ^ bdigit ^ carry + '0') + result; 
        carry = adigit + bdigit + carry >= 2;
    }

    return result;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42568次
    • 积分:2516
    • 等级:
    • 排名:第14654名
    • 原创:215篇
    • 转载:20篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论