Java Solution


  • 0
    L
    class Solution {
        public String addBinary(String a, String b) {
            int m = a.length();
            int n = b.length();
            int carry = 0;
            StringBuilder newString  = new StringBuilder();
            int sum =0;
            int digit = 0;
            for(int i=m-1,j=n-1;;i--,j--){
                if(i>=0 && j>=0)
                    sum = Integer.valueOf(a.substring(i,i+1))+Integer.valueOf(b.substring(j,j+1))+carry;
                if(i<0 && j>=0)
                    sum = Integer.valueOf(b.substring(j,j+1))+carry;
                if(i>=0 && j<0)
                    sum = Integer.valueOf(a.substring(i,i+1))+carry;
                if(i<0 && j<0 && carry>0){
                    newString.insert(0,""+carry);
                    return newString.toString();
                }
                if(i<0 && j<0 && carry==0)
                    return newString.toString();
                
                carry = sum/2;
                digit = sum%2;
                newString.insert(0,""+digit);
    
            }
        }
    }
    

Log in to reply
 

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