In Javascript (2) approaches


  • 1
    A

    (1) Simple approach using parseInt

    /* Possible problem with Javascript is about limiatation of 2^32 or 2^64 BITS capacity / limitations */ 
    var addBinary = function(a, b) {
        var x = parseInt(a, 2);
        var y = parseInt(b, 2);
        var z = x + y;
        return z.toString(2);
    };
    
    

    (2) String parsing. Elementary school math style.

    var addBinary = function(a, b) {
        var i = a.length - 1;
        var j = b.length - 1;
        var answer = "";
        var carry = 0;
        
        while(i >= 0 || j >= 0) {
            var sum = carry;
            /* Following conditions added to avoid "undefined", "Out of Index" Errors */
            if(j >= 0) {
                sum += parseInt(b.charAt(j));
                j--;
            }
            if(i >= 0) {
                sum += parseInt(a.charAt(i));
                i--;
            }
            /* 
                Sum Can be 0 (00) or 1 (01) or 2 (10) or 3 (11)
                Based on the "sum" value, we decide carry and sum.
            */
            if(sum == 2) {
                carry = 1;
                sum = 0;
            } else if(sum > 2) {
                carry = 1;
                sum = 1;
            } else {
                carry = 0;
            }
            /* Append Binary equivalent of the current iteration sum to final answer */
            answer = sum.toString(2) + answer;
            
        }
        /* Many times, developer can forget to consider carry remaining at the end of all iterations */
        if(carry > 0) {
            answer = carry.toString(2) + answer;
        }
        return answer;
    };
    
    

Log in to reply
 

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