【Leetcode】67. 二进制求和

题目描述:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

解题思路:

模拟加法器,每位都有和与进位。下一位是加数,被加数和进位之间的运算,这里直接是字符串运算,我就都列举了一下。

AC代码:

class Solution {
public:
    string addBinary(string a, string b)
    {
        char carry = '0';
        char ret = '0';
        string res = "";
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());

        for (int i = 0; i < max(a.size(), b.size()); i++)
        {
            char c1 = (i >= a.size()) ? '0' : a[i];
            char c2 = (i >= b.size()) ? '0' : b[i];
            if (c1 == '1'&&c2 == '1'&&carry == '1')
            {
                carry = '1';
                ret = '1';
            }
            else if (c1 == '1'&&c2 == '1'&&carry == '0')
            {
                carry = '1';
                ret = '0';
            }
            else if (c1 == '1'&&c2 == '0'&&carry == '1')
            {
                carry = '1';
                ret = '0';
            }
            else if (c1 == '1'&&c2 == '0'&&carry == '0')
            {
                carry = '0';
                ret = '1';
            }
            else if (c1 == '0'&&c2 == '1'&&carry == '1')
            {
                carry = '1';
                ret = '0';
            }
            else if (c1 == '0'&&c2 == '1'&&carry == '0')
            {
                carry = '0';
                ret = '1';
            }
            else if (c1 == '0'&&c2 == '0'&&carry == '1')
            {
                carry = '0';
                ret = '1';
            }
            else if (c1 == '0'&&c2 == '0'&&carry == '0')
            {
                carry = '0';
                ret = '0';
            }
            res += ret;
        }
        if (carry == '1')
        {
            res += carry;
        }
        reverse(res.begin(), res.end());

        return res;
    }
};

 

你可能感兴趣的:(LeetCode)