Add Binary

https://leetcode.com/problems/add-binary/

Description

Add Binary

Given two binary strings a and b, return their sum as a binary string.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= a.length, b.length <= 104

  • a and b consist only of '0' or '1' characters.

  • Each string does not contain leading zeros except for the zero itself.

Solution

Solution 1 use carry

class Solution {
public:
    string addBinary(string a, string b) {
        int carry = 0; 
        string ans = ""; 
        for (int i = a.size()-1, j = b.size()-1; i >= 0 or j >= 0; --i, --j) {
            if (i >= 0) carry += a[i] - '0'; 
            if (j >= 0) carry += b[j] - '0'; 
            ans = to_string(carry & 1) + ans; 
            carry >>= 1; 
        }
        return carry? '1' + ans : ans; 
    }
};

Solution 2

最后更新于

这有帮助吗?