LeetCode #67 Add Binary 二进制求和

67 Add Binary 二进制求和

Description:
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:

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

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

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

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

示例:

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

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

思路:

设置进位符号, 从后往前遍历
时间复杂度O(n), 空间复杂度O(n)

代码:
C++:

class Solution 
{
public:
    string addBinary(string a, string b) 
    {
        string result = "";
        int i = a.size() - 1, j = b.size() - 1, carry = 0;
        while (i >= 0 or j >= 0) 
        {
            int p = i >= 0 ? a[i--] - '0' : 0, q = j >= 0 ? b[j--] - '0' : 0;
            int temp = p + q + carry;
            result = to_string(temp % 2) + result;
            carry = temp / 2;
        }
        return carry == 1 ? "1" + result : result;
    }
};

Java:

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        while (i >= 0 || j >= 0) {
            int p = i >= 0 ? a.charAt(i--) - '0' : 0;
            int q = j >= 0 ? b.charAt(j--) - '0' : 0;
            int temp = p + q + carry;
            result.append(temp % 2);
            carry = temp / 2;
        }
        if (carry == 1) result.append(carry);
        return result.reverse().toString();
    }
}

Python:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, 2) + int(b, 2))[2:]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容