O(n) time 2ms Java solution


  • 0
    Z
    public class Solution {
        public String addBinary(String a, String b) {
            byte carry = 0;
            char[] sumChars = new char[Math.max(a.length(), b.length()) + 1];
            int sum = 0;
            for (int i = a.length() - 1, j = b.length() - 1, k = sumChars.length - 1; i >= 0 || j >= 0; i--, j--, k--) {
                sum = carry + (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0);
                sumChars[k] = (char) (sum % 2 + '0');
                carry = (byte) (sum / 2);
                sum = 0;
            }
            if (carry == 0) {
                return new String(sumChars, 1, sumChars.length - 1);
            } else {
                sumChars[0] = (char) (1 + '0');
                return new String(sumChars);
            }
        }
    }
    

Log in to reply
 

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