My simple 4ms JAVA Solution. Clean and consice.


  • 12
      public String addBinary(String a, String b) {
        int aLength = a.length();
        int bLength = b.length();
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        while(Math.max(aLength, bLength) > 0) {
          int aNum = aLength > 0 ? (a.charAt(aLength---1) - '0') : 0;
          int bNum = bLength > 0 ? (b.charAt(bLength---1) - '0') : 0;
          int cNum = aNum + bNum + carry;
          sb.append(cNum%2);
          carry = cNum / 2;
        }
        return (carry == 1)?sb.append(1).reverse().toString():sb.reverse().toString();
      }

  • 0

    Test of "0001" + "1" failed. Should return "10" but "0010". Though this kind of test cases is not included in tests.


Log in to reply
 

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