Simple java solution


  • 1
    M
    public String addBinary(String a, String b) {
            String r ="";
            int p =0;
            for(int i=a.length()-1, j=b.length()-1; i>=0 || j>=0; i--,j--)
            {
                int va = 0;
                if(i>=0 && a.charAt(i) == '1')
                    va=1;
                int vb = 0;
                if(j>=0 && b.charAt(j) == '1')
                    vb=1;
                switch (p+va+vb)
                {
                    case 1: r = "1"+r;p=0;break;
                    case 2: r = "0"+r;p=1;break;
                    case 3: r = "1"+r;p=1;break;
                    default:r = "0"+r;p=0;break;
                }
            }
            if(p==1) r = "1"+r;
            return r;
        }
    
    

Log in to reply
 

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