Java solution with carry without reverse string


  • 0
    T
    public String addBinary(String a, String b) {
            int alen = a.length() - 1, blen = b.length() - 1, carry = 0;
            StringBuilder sb = new StringBuilder();
            while (alen > -1 || blen > -1 || carry != 0){
                if (alen > -1){
                    carry += a.charAt(alen) - '0';
                    alen--;
                }
                if (blen > -1){
                    carry += b.charAt(blen) - '0';
                    blen--;
                }
                sb.insert(0, carry % 2);
                carry = carry / 2;
            }
            return sb.toString();
        }
    

Log in to reply
 

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