Add Binary

LeetCode Q 67 - Add Binary

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"

Solution

Code:

public String addBinary(String a, String b) {
  
  StringBuilder sb = new StringBuilder();
  int carry = 0, i = a.length() - 1, j = b.length() - 1;
  
  while (i >= 0 || j >= 0) {
    int num = carry;
    if (i >= 0) num += a.charAt(i--) - '0';
    if (j >= 0) num += b.charAt(j--) - '0';
    
    sb.append(num % 2);
      carry = num / 2;
  }
  
  if (carry == 1)
    sb.append('1');
  
  return sb.reverse().toString();
}

   Reprint policy


《Add Binary》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC