LeetCode Add Binary

67. Add Binary

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4
  • Each string is either "0" or doesn’t contain any leading zero.

把两个二进制字符串相加,注意进位即可。 把while (i >= 0 && j >= 0)改成while (i >= 0 || j >= 0),这样就只需要一个while循环了,只不过循环体里面求sum需要判断一下i,j。完整代码如下:

class Solution {
public:
    string addBinary(string a, string b)
    {
        int i = a.size() – 1, j = b.size() – 1;
        string ans = "";
        bool carry = false;
        while (i >= 0 || j >= 0) {
            int sum = (i >= 0 ? (a[i] – ‘0’) : 0) + (j >= 0 ? (b[j] – ‘0’) : 0);
            sum += carry ? 1 : 0;
            if (sum >= 2) {
                ans.push_back(sum – 2 + ‘0’);
                carry = true;
            }
            else {
                ans.push_back(‘0’ + sum);
                carry = false;
            }
            i–;
            j–;
        }
        if (carry)
            ans.push_back(‘1’);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

本代码提交AC,用时3MS。

二刷。更简洁的代码:

class Solution {
public:
	string addBinary(string a, string b) {
		int m = a.size(), n = b.size();
		string ans = "";
		int i = m - 1, j = n - 1;
		int carry = 0;
		while (i >= 0 || j >= 0) {
			int u = i >= 0 ? a[i] - '0' : 0;
			int v = j >= 0 ? b[j] - '0' : 0;
			int sum = u + v + carry;
			carry = sum / 2;
			ans.push_back('0' + (sum % 2));
			--i;
			--j;
		}
		if (carry != 0)ans.push_back('1');
		reverse(ans.begin(), ans.end());
		return ans;
	}
};

本代码提交AC,用时4MS。

Leave a Reply

Your email address will not be published. Required fields are marked *