R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Decimal/Binary Conversion}

The Question

Write 2 functions, one that takes the a number in base 10 (decimal) and converts it to the string representation of that number in base 2 (binary), and one that converts back.

The Algorithm


    203                 ""

    101                "1"

    50                "11"

    25               "011"

    12              "1011"

    6              "01011"

    3             "001011"

    1            "1001011"

    0           "11001011"

The Solution - Part 1


    function decimalToBinary(num) {
        if (!num) return "";
        return decimalToBinary(Math.floor(num/2)) + num%2;   
    }
        function decimalToBinary(num) {
            var power = 2;
            var binaryStr = '';
            while(num) {
                var remainder = num % power;
                var digit = remainder ? 1 : 0;
                binaryStr = digit + binaryStr;
                num = num - remainder;
                power *= 2;
            }
            return binaryStr;
        }   

The Solution - Part 2


    function binaryToDecimal(numStr) {
        if (!numStr.length) return 0;
        return binaryToDecimal(numStr.slice(0, -1))*2 
            + Number(numStr[numStr.length-1]);
    }




    OR




    function binaryToDecimal (numStr) {
        var sum = 0;
        var reversedStr = numStr.split('').reverse();
        for (var i = 0; i < reversedStr.length; i++) {
            sum += Math.pow(2, i) * reversedStr[i];
        }
        return sum;
    }
Made with Slides.com