A simple Java solution


  • 0
    L
    public String addBinary(String a, String b) {        
            StringBuilder builder = new StringBuilder();
            int i=a.length()-1;
            int j=b.length()-1;
            int carry = 0;
            while(i>=0 || j>=0 || carry>0) {
                int val = carry;
                if(i>=0) {
                    val += a.charAt(i)-'0';
                    i--;
                }
                if(j>=0) {
                    val += b.charAt(j)-'0';
                    j--;
                }
                
                carry = val/2;
                builder.append(val%2);
            }
            
            return builder.reverse().toString();
        }
    

Log in to reply
 

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