简体   繁体   中英

Creating a Recursive Binary to Decimal Function

I am trying to create a recursive Binary to Decimal Function. Here is my current attempt:

function decToBin(num){
    if(num >= 1){
        (num % 2); //I have to STORE? this somewhere
        decToBin(Math.floor(num/2));
    } 
    // return my stored value here


}

I want to take the modulo of the new number each until it is 0. How do I store each pass of the function? Do I just make a global variable outside the scope of the function, or is there a better way? Thanks!

Usually with recursive functions, you combine the "current value" with the return value of the next iteration. So, you take all the "return values" and combine them all together.

In this case, you want something like:

return decToBin(Math.floor(num/2))+(num % 2);

Thus making your entire function:

function decToBin(num){
    if(num >= 1){
        return decToBin(Math.floor(num/2))+(num % 2);
    } 
    return '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM