67. Add Binary(二进制求和)

2023-05-06 17:07:08 浏览数 (1)

题目地址:https://leetcode.com/problems/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 1:

代码语言:javascript复制
Input: a = "11", b = "1"
Output: "100"

Example 2:

代码语言:javascript复制
Input: a = "1010", b = "1011"
Output: "10101"

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

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

示例 1:

代码语言:javascript复制
输入: a = "11", b = "1"
输出: "100"

示例 2:

代码语言:javascript复制
输入: a = "1010", b = "1011"
输出: "10101"
代码语言:javascript复制
class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1, j = b.length() - 1;
        Stack<String> stack = new Stack<String>();
        int jin = 0, num_a, num_b;
        while (i >= 0 && j >= 0){
            num_a = a.charAt(i--) == '0' ? 0 : 1;
            num_b = b.charAt(j--) == '0' ? 0 : 1;
            int temp = num_a   num_b   jin;
            stack.push(temp % 2 == 0 ? "0" : "1");
            jin = temp >> 1;
        }
        while (i >= 0) {
            num_a = a.charAt(i--) == '0' ? 0 : 1;
            int temp;
            if (jin != 0) {
                temp = num_a   jin;
            } else {
                temp = num_a;
            }
            stack.push(temp % 2 == 0 ? "0" : "1");
            jin = temp >> 1;
        } 
        while (j >= 0) {
            num_b = b.charAt(j--) == '0' ? 0 : 1;
            int temp;
            if (jin != 0) {
                temp = num_b   jin;
            } else {
                temp = num_b;
            }
            stack.push(temp % 2 == 0 ? "0" : "1");
            jin = temp >> 1;
        }
        if (jin != 0) {
            stack.push("1");
        }
        StringBuilder str = new StringBuilder();
        while (!stack.isEmpty()) {
            str.append(stack.pop());
        }
        return str.toString();
    }
}

写了半天发现评论区的一位大佬直接用BigInteger解决了,感觉智商被碾压。。。,贴上代码

代码语言:javascript复制
import java.math.*;
class Solution {
    public String addBinary(String a, String b) {
        return (new BigInteger(a, 2).add(new BigInteger(b, 2))).toString(2);
    }
}

0 人点赞