Implement method that returns the binary string which is a sum of 2 binary strings

Example 1: a = “1000”, b = “111”: the result should be “1111”

Example 2: a = “1111”, b = “1”: the result should be “10000”

Solution in Java

    public String binarySum(String a, String b) {
        int sum = 0;
        String sumString = "";
        int aLen = a.length();
        int bLen = b.length();
        for (int i = 1; i <= Math.max(a.length(), b.length()); i++) {
            sum += (i <= aLen ? a.charAt(aLen - i) - '0' : 0) + (i <= bLen ? b.charAt(bLen - i) - '0' : 0);
            sumString = (char)((sum % 2) + '0' ) + sumString;
            sum = sum / 2;
        }
        return sum == 0 ? sumString : "1" + sumString;
    }