【Add Binary】-(Java)

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.

completion:

class Solution {
    public String addBinary(String a, String b) {
        String min_bin;
        String max_bin;
        StringBuilder s = new StringBuilder();
        if (a.length() >= b.length()) {
            min_bin = b;
            max_bin = a;
        } else {
            min_bin = a;
            max_bin = b;
        }
        int[] number = new int[max_bin.length() + 1];
        int carry = 0;
        for (int i = 1; i <= max_bin.length(); i++) {
            int z;
            if (min_bin.length() - i >= 0) {
                int x = min_bin.charAt(min_bin.length() - i) - '0';
                int y = max_bin.charAt(max_bin.length() - i) - '0';
                z = x + y + carry;
            } else {
                int x = max_bin.charAt(max_bin.length() - i) - '0';
                z = x + carry;
            }
            s.insert(0, z % 2);
            carry = z / 2;
        }
        if (carry == 1) {
            s.insert(0, carry);
        }
        return s.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值