Simple Java Solution


  • 0
    P
        public String addBinary(String a, String b) {
            int carryIn = 0;
            int i = a.length() - 1, j = b.length() - 1;
            StringBuilder sum = new StringBuilder();
    
            while (i >= 0 || j >= 0) {
                int ak = i < 0? 0 : (a.charAt(i--) - '0');
                int bk = j < 0? 0 : (b.charAt(j--) - '0');
                int carryOut = (ak & bk) | (ak & carryIn) | (bk & carryIn);
                sum.append((ak ^ bk ^ carryIn));
                carryIn = carryOut;
            }
            return carryIn == 1? 
                      sum.append(carryIn).reverse().toString() : sum.reverse().toString();
        }
    

    Not a good idea to use insert() instead of append() then reverse(); which will cause O(n^2) instead of O(n).


Log in to reply
 

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