Easy understand java solution


  • 0
    Q
    public String addBinary(String a, String b) {
            if(a.length()==0&&b.length()==0) return "0";
            int carry=0;
            int i=a.length()-1;
            int j=b.length()-1;
            StringBuffer sb=new StringBuffer();
            while (i>=0||j>=0){
                int sum=0;
                if (i<0) sum=(b.charAt(j)-'0')+carry;
                else if(j<0) sum=(a.charAt(i)-'0')+carry;
                else sum=(a.charAt(i)-'0')+(b.charAt(j)-'0')+carry;
                i--;
                j--;
                if (sum>2) {
                    sb.append("1");
                    carry=1;}
                else if (sum>1){
                    sb.append("0");
                    carry=1;}
                else {sb.append(sum);
                    carry=0;}
            }
            if (carry>0) sb.append(carry);
            return sb.reverse().toString();
        
        }

Log in to reply
 

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