My Solution in Java


  • 0
    W
    public String addBinary(String a, String b) {
    
        char[] at = a.toCharArray();
        char[] bt = b.toCharArray();
        int length = at.length > bt.length ? at.length : bt.length;
    
        char[] result = new char[length + 1];
        int carry = 0;
    
        for (int i = 0; i < length; i++) {
          int ai, bi;
          if ((at.length - 1 - i) >= 0) {
            ai = at[at.length - 1 - i] - '0';
          } else {
            ai = 0;
          }
    
          if ((bt.length - 1 - i) >= 0) {
            bi = bt[bt.length - 1 - i] - '0';
          } else {
            bi = 0;
          }
          result[length - i] = (ai + bi + carry) % 2 == 1 ? '1' : '0';
          carry = (ai + bi + carry) / 2;
        }
    
        result[0] = carry == 1 ? '1' : '0';
    
        return carry == 0 ? String.valueOf(result).substring(1) : String.valueOf(result);
    }
    

Log in to reply
 

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