leetcode 66:Add Binary

原创 2015年11月19日 22:00:57

题目:

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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode 21_Merge Two Sorted Lists & leetcode_258 Add Digits & leetcode_66plus one

l leetcode 21_Merge Two Sorted Lists 题目:Merge two sorted linked lists and return it as a new list...

leetcode之Add Binary

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" ...

LeetCode Add to List 617 Merge Two Binary Trees (深度优先搜索)

LeetCode Add to List 617 Merge Two Binary Trees (深度优先搜索)

LeetCode-67. Add Binary

问题描述Given two binary strings, return their sum (also a binary string). For example, a = “11” b = ...

leetcode--67. Add Binary

leetcode

[LeetCode] Add Binary

给定两个表示二进制的字符串,返回它们的和。

?【Leetcode】67. Add Binary

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Ret...

Add Binary | leetcode 67 【Java解题报告】

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Re...

【leetcode c++】67 Add Binary

Add Binary Given two binary strings, return their sum(also a binary string).   For example, a = ...
  • hqq39
  • hqq39
  • 2015年06月30日 12:09
  • 402

[LeetCode] 67. Add Binary java

/**67. Add Binary * @param a * @param b * @returnString 字符串模拟二进制位相加运算 */ ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 66:Add Binary
举报原因:
原因补充:

(最多只允许输入30个字)