LeetCode.067.Add Binary 二进制求和

题目描述

67 Add Binary https://leetcode-cn.com/problems/add-binary/ 给你两个二进制字符串,返回它们的和(用二进制表示)。

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

示例 1:

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

示例 2:

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

提示: 每个字符串仅由字符 '0' 或 '1' 组成。 1 <= a.length, b.length <= 10^4 字符串如果不是 "0" ,就都不含前导零。


相似题目

LeetCode.371.Sum of Two Integers 不用加减号计算整数加法 LeetCode.067.Add Binary 二进制求和

LeetCode.剑指offer.064.计算1到n的和


解题过程

直接模拟二进制加法

时间复杂度 O(n) n 是 a,b 长度的较大值, 空间复杂度 O(1)

private static class SolutionV202006 {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1, j = b.length() - 1;
        byte carry = 0; // 进位
        while (i >= 0 || j >= 0 || carry != 0) {
            carry += i >= 0 ? a.charAt(i--) - '0' : 0;
            carry += j >= 0 ? b.charAt(j--) - '0' : 0;
            sb.insert(0, String.valueOf(carry & 1));
            carry >>= 1;
        }
        return sb.toString();
    }
}

GitHub代码

algorithms/leetcode/leetcode/_067_AddBinary.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_067_AddBinary.java