Add Two Binary Strings

easy Strings

Problem

Two binary numbers are given as words of 0 and 1 (they can be longer than any built-in number type). Print their sum as a binary number without leading zeros (print 0 if the sum is zero). Add digit by digit from the right with a carry, like on paper.

Constraints

  • 1 <= length <= 10^4

Examples

Input

11 1

Output

100

Input

1010 1011

Output

10101

Solutions

Best approachTime O(n)Space O(n)

Integer.parseInt(a, 2) would overflow for long inputs, so we add digit by digit. The same carry idea works for decimal addition and for linked-list numbers.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process two words.
 * Input   : Two words separated by a space.
 * Output  : The binary sum.
 * Approach: Two binary words.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String a, String b) {
        // Step 1: Start at the last digit of both words. The carry is what we move to the next digit.
        StringBuilder result = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        while (i >= 0 || j >= 0 || carry > 0) {
            // Step 2: Add the two digits (a missing digit counts as 0) and the carry.
            int sum = carry;
            if (i >= 0) {
                sum += a.charAt(i--) - '0';
            }
            if (j >= 0) {
                sum += b.charAt(j--) - '0';
            }
            // Step 3: The new digit is sum % 2. The new carry is sum / 2.
            result.append(sum % 2);
            carry = sum / 2;
        }
        // Step 4: We built the answer from the right, so reverse it. Remove leading zeros, but keep one digit.
        String text = result.reverse().toString().replaceFirst("^0+(?=.)", "");
        return text.isEmpty() ? "0" : text;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. What are the only possible values of carry here?