67. Add Binary

Title address: 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:

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

Example 2:

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

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 + gen;
            } 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 + gen;
            } 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();
    }
}

After writing for a long time, I found that a big guy in the comment area solved it directly with BigInteger, and I felt that my IQ was crushed. . . , paste the code

import java.math.*;
class Solution {
    public String addBinary(String a, String b) {
        return (new BigInteger(a, 2).add(new BigInteger(b, 2))).toString(2);
    }
}

============================== I am a slow programmer ============= =============

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325947412&siteId=291194637