67. 二进制求和

给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。

示例 1:

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

示例 2:

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

提示:

  • 1 <= a.length, b.length <= 104
  • a 和 b 仅由字符 '0' 或 '1' 组成
  • 字符串如果不是 "0" ,就不含前导零

力扣题解:. - 力扣(LeetCode)

方法2:(0ms)

    public String addBinary(String a, String b) {//测试提交时间
        if (a.length() < b.length()) {
            return addBinary(b, a);
        }
        char[] sum = new char[a.length() + 1];
        int indexA = a.length() - 1, diffLen = a.length() - b.length();
        char carry = '0';
        while (indexA > -1) {
            char bitB = indexA - diffLen > -1 ? b.charAt(indexA - diffLen) : '0';
            if (a.charAt(indexA) == bitB) {
                sum[indexA-- + 1] = carry;
                carry = bitB;
            } else {
                sum[indexA-- + 1] = carry == '0' ? '1' : '0';
            }
        }
        sum[0] = carry;
        return carry == '1' ? new String(sum, 0, a.length() + 1) : new String(sum, 1, a.length());
    }

方法3:(1ms)

    public String addBinary(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int ca = 0;
        for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
            int sum = ca;
            sum += i >= 0 ? a.charAt(i) - '0' : 0;
            sum += j >= 0 ? b.charAt(j) - '0' : 0;
            ans.append(sum % 2);
            ca = sum / 2;
        }
        ans.append(ca == 1 ? ca : "");
        return ans.reverse().toString();
    }

方法4:(2ms)

    public String addBinary(String a, String b) {
        Deque stack1 = new ArrayDeque<>();
        Deque stack2 = new ArrayDeque<>();
        for (char c : a.toCharArray()) {
            stack1.push(c);
        }
        for (char c1 : b.toCharArray()) {
            stack2.push(c1);
        }
        StringBuffer sb = new StringBuffer();
        int carry = 0, sum = 0;
        while (stack1.size() > 0 || stack2.size() > 0) {
            int a1 = stack1.size() == 0 ? 0 : stack1.pop() - '0';
            int a2 = stack2.size() == 0 ? 0 : stack2.pop() - '0';
            sum = a1 + a2 + carry;
            int mod = sum % 2;
            carry = sum / 2;
            sb.append(mod);
        }

        if (carry == 1) sb.append(1);
        return sb.reverse().toString();
    }

你可能感兴趣的:(java,前端,linux)