Consise Java solution. 11 lines


  • 6
    Z
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for(int i=a.length()-1,j=b.length()-1;i>=0 || j>=0;i--,j--){
            int v1 = (i<0)?0:a.charAt(i)-'0';
            int v2 = (j<0)?0:b.charAt(j)-'0';
            int val = (v1+v2+carry)%2;
            carry = (v1+v2+carry)/2;
            sb.insert(0,(char)(val+'0'));
        }
        if(carry == 1) sb.insert(0,'1');
        return sb.toString();
    }

  • 0
    A

    could I ask why in this line: sb.insert(0,(char)(val+'0'));
    val should add '0'?
    since val is int, then (char) could already change val from int to char?
    Thx!


  • 0
    Z

    you are right, use sb.insert(0,val) is better


  • 0
    M

    the original code is correct and add '0' is necessary!


Log in to reply
 

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