Beats 90% clean Java solution


  • 0
    L
    public String addBinary(String a, String b)
      {
        char[] arr = new char[Math.max(a.length(), b.length())];
        int carry = 0;
        int count = arr.length - 1;
        for (int i = a.length() - 1, j = b.length() - 1; i >= 0
            || j >= 0; i--, j--)
        {
          int val = carry;
          carry=0;
          if (i >= 0)
          {
            val += a.charAt(i) - '0';
          }
          if (j >= 0)
          {
            val += b.charAt(j) - '0';
          }
          if (val == 0 || val == 1)
          {
            arr[count--] = (char) (val + '0');
          }
          else if (val == 2)
          {
            arr[count--] = '0';
            carry = 1;
          }
          else if (val == 3)
          {
            arr[count--] = '1';
            carry = 1;
          }
        }
        if (carry == 1)
        {
          char[] newarr = new char[arr.length + 1];
          System.arraycopy(arr, 0, newarr, 1, arr.length);
          newarr[0] = '1';
          arr = newarr;
        }
        return new String(arr);
      }
    

Log in to reply
 

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