Super short Java code


  • 10
    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder sum = new StringBuilder();
            int i = a.length() - 1;
            int j = b.length() - 1;
            int carry = 0;
            while (i >= 0 || j >= 0 || carry == 1) {
                int digitA = i < 0 ? 0 : a.charAt(i--) - '0';
                int digitB = j < 0 ? 0 : b.charAt(j--) - '0';
                sum.insert(0, (digitA + digitB + carry) % 2);
                carry = (digitA + digitB + carry) / 2;
            }
            return sum.toString();
        }
    }

  • -2
    T

    Nice code :) But should you be removing the leading zeros in your answer?


  • 0

    there is no leading zeros. digitA and digitB and carry can not be equal to 0 at the same time.


  • 0
    T

    what if a = 000001 , b = 0000000001 - I assumed that the answer should have minimum possible digits (ie, 10), but that may not be a requirement.


  • 0

    the input does not have leading zero, therefore output does not neither.


  • 0
    T

    I agree that if the input doesn't have leading zeros, the output will not. But no where in the question is it explicitly mentioned that the input will not have leading zeros. At least personally in an interview situation, I will not make that assumption.


  • 0

    If that is the case, then mowhere is mentioned that the output must contain no leading zero. It is not fair that you assume input may have leading zero while output must not.


  • 1

    No, this is super short :p

    String addBinary(String a, String b) {
        return new BigInteger(a, 2).add(new BigInteger(b, 2)).toString(2);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.