Simple Java & clean java:)


  • 2
    S
    public String addBinary(String a, String b) {
            if(a == "") return b;
            if(b == "") return a;
            String res = "";
            int c = 0;
            int i = a.length()-1;
            int j = b.length()-1;
            
            while(i>=0 || j>=0) {
                int curIntA = i>-1?Character.getNumericValue(a.charAt(i)):0;
                int curIntB = j>-1?Character.getNumericValue(b.charAt(j)):0;
                res=(curIntA ^ curIntB ^ c)+res;
                c = (curIntA+curIntB+c) >= 2 ? 1 : 0;
                i--;
                j--;
            }
            
            return c != 0 ? c+res : res;
        }

  • 0
    S

    @sara13 You will make your code faster if you use a StringBuilder and just append(). At the end all you have to do is to return sb.reverse().toString();


Log in to reply
 

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