My java solution 4ms


  • 1
    R
        public class Solution {
         public String addBinary(String a, String b) {
            int i = a.length()-1;
            int j=b.length()-1;
            int carry = 0;
            String res = new String();
            while(i>=0||j>=0){
                int bit1 = (i>=0)?((a.charAt(i--)=='1')?1:0):0;
                int bit2 = (j>=0)?((b.charAt(j--)=='1')?1:0):0;
                int value = bit1^bit2^carry;
                carry = bit1&carry|bit2&carry|bit1&bit2;
                res = (String.valueOf(value)).concat(res);
            }
            
            return carry==1?String.valueOf(1).concat(res):res;
        }
    }

Log in to reply
 

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