Header: I am console.logging what I want to return.
I want to have a data structure store the necessary powers of 2 that I am calculating, but because it's recursive, I'm having trouble saving the output in a string or array without the data structure being overwritten each function call.
It's almost like I want to use request.session
. How do I store what I'm console logging?
I tried:
if(!this) {then that}
But this is never there so it runs every time. Maybe passing it through the parameter is a way to solve this but the parameter is only n, and I want the function to only take in n and then output some information relevant to the binary equivalent, but I am probably going about it all wrong.
I think it's interesting that I can console.log
it but I can't push it to an array.
How can I proceed?
function binary(n){
if(n == 0){
console.log("The end");
return 0;
}
var b, x;
for(var i = 0; i <= 10; i++){
b = Math.pow(2,i);
if(b > n){
var p = i-1;
console.log("2 to the",p, "is on");
x = Math.pow(2,i-1);
n = n-x;
return binary(n);
}
}
}
binary(12);
binary(365);
// 12 == 2^3(1) + 2^2(1) + 2^1(0) + 2^0(0)
// 12 == 1100
Footer:
[Running] node "/Users/maxwelljann/Desktop/cracking_the_coding_interview/b3.js"
2 to the 3 is on
2 to the 2 is on
The end
2 to the 8 is on
2 to the 6 is on
2 to the 5 is on
2 to the 3 is on
2 to the 2 is on
2 to the 0 is on
The end