LeetCode 67. Add Binary

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 67. Add Binary相关的知识,希望对你有一定的参考价值。

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

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

这个题目只要注意各种情况你就成功了一大半,特别要注意的是对进位赋值后可能产生的变化,以及最后一位进位为1时,

我们要把这个1插进来。同时注意字符串的低位是我们数值的高位

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(begin(a), end(a));
        reverse(begin(b), end(b));
        string result;
        char num = 0;
        int i = 0;
        for (;i < a.size() && i < b.size();++i)
        {
            if (a[i] == 0&&b[i] == 0&&num == 0)
            {
                result.insert(begin(result), 0);
            }
            if (a[i] == 1&&b[i] == 1&&num == 1)
            {
                result.insert(begin(result), 1);
            }
            if ((a[i] == 0&&b[i] == 1&&num == 1) || (a[i] == 1&&b[i] == 0&&num == 1) ||
                (a[i] == 1&&b[i] == 1&&num == 0))
            {
                result.insert(begin(result), 0);
                num = 1;
            }
            if (a[i] == 1&&b[i] == 0&&num == 0 || a[i] == 0&&b[i] == 1&&num == 0 ||
                a[i] == 0&&b[i] == 0&&num == 1)
            {
                result.insert(begin(result), 1);
                num = 0;
            }
        }
        if (i == a.size())
        {
            for (;i < b.size();++i)
            {
                if (b[i] == 0&&num == 0)
                    result.insert(begin(result), 0);
                if (b[i] == 0&&num == 1 || b[i] == 1&&num == 0)
                {
                    result.insert(begin(result), 1);
                    num = 0;
                }
                if (b[i] == 1&&num == 1)
                    result.insert(begin(result), 0);
            }
        }
        else
        {
            for (;i < a.size();++i)
            {
                if (a[i] == 0&&num == 0)
                    result.insert(begin(result), 0);
                if (a[i] == 1&&num == 1)
                    result.insert(begin(result), 0);
                if (a[i] == 0&&num == 1 || a[i] == 1&&num == 0)
                {
                    result.insert(begin(result), 1);
                    num = 0;
                }
                
            }
        }
        if (num == 1)result.insert(begin(result), 1);
        return result;
    }
};

 

以上是关于LeetCode 67. Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode----67. Add Binary(java)

leetcode67. Add Binary

LeetCode 67. Add Binary

LeetCode 67. Add Binary

Leetcode 67. Add Binary

leetcode 67 Add Binary