Java solution 5ms using xor


  • 0
    S
     public String addBinary(String a, String b) {
            StringBuilder sb = new StringBuilder();
            int la = a.length();
            int lb = b.length();
            int Na = 0;
            for(int ia=la-1, ib=lb-1;ia>=0 ||ib>=0; ia--,ib--)
            {
                int aa =0;
                int bb =0;
                if (ia >=0)aa = (a.charAt(ia)-'0');
                if (ib >=0)bb = (b.charAt(ib)-'0');
                int c = (Na ^ aa ^ bb);
                sb.insert(0,c);
                Na = (Na+aa+bb)/2;
            }
            if(Na>0)sb.insert(0,Na);
            return sb.toString();
        }

Log in to reply
 

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