My java solution


  • -2
    X
    public class Solution {
        public String addBinary(String a, String b) {
            int aLength=a.length();
            int bLength=b.length();
            if(aLength==0) return b;
            if(bLength==0) return a;
            
            int carry=0;
            StringBuffer buffer=new StringBuffer();
            for(int i=0;i<aLength||i<bLength;i++){
                int n1,n2;
                
                if(i>=aLength) n1=0;
                else n1=Integer.parseInt(String.valueOf(a.charAt(aLength-1-i)));
                
                if(i>=bLength) n2=0;
                else n2=Integer.parseInt(String.valueOf(b.charAt(bLength-1-i)));
            
                buffer.insert(0,(carry+n1+n2)%2);
                if(carry+n1+n2>1){
                    carry=(carry+n1+n2)/2;
                }
                else carry=0;
            }
            if(carry==1) buffer.insert(0,1);
            
            return buffer.toString();
        }
    }

Log in to reply
 

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