Recursive Java Solution


  • 0
    A

    A pretty simple to understand (hopefully) recursive solution.

    public class Solution {
        public String addBinary(String a, String b) {
            return addBinaryHelper(a, b, a.length(), b.length(), 0).toString();        
        }
        
        private StringBuilder addBinaryHelper(String a, String b, int aLen, int bLen, int carry){
            if (aLen <=0 && bLen <=0){
                StringBuilder sb = new StringBuilder();
                if (carry == 1) { sb.append('1'); }
                return sb;
            }
            int lastA = (aLen <= 0) ? 0 : a.charAt(aLen-1)-'0';
            int lastB = (bLen <= 0) ? 0 : b.charAt(bLen-1)-'0';
            int sum = lastA + lastB + carry;
            carry = sum / 2;
            int place = sum % 2;
            return addBinaryHelper(a,b,aLen-1,bLen-1,carry).append(place);
        }
    
    }
    

Log in to reply
 

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