My Java Solution


  • 0
    B

    This is my solution, Runtime: 308 ms, how can i get faster.

    public class Solution {
        public String addBinary(String a, String b) {
            char[] ac = ("0" + a).toCharArray(), bc = b.toCharArray();
            if (a.length() < b.length()) {
                ac = ("0" + b).toCharArray();
                bc = a.toCharArray();
            }
    
            for (int i = ac.length - 1; i >= 0; i--) {
                int bar = bc.length - ac.length + i;
                if (bar >= 0)
                    ac[i] += (bc[bar] - 48);
                if (ac[i] > 49) {
                    ac[i - 1] += (ac[i] - 48) / 2;
                    ac[i] = (char) (ac[i] % 2 + 48);
                }
            }
            return String.valueOf(ac).replaceAll("^0", "");
        }
    }

Log in to reply
 

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