+ 2
Please. Can somebody explain me why this code output is: 110 ?
4 Antworten
+ 3
Hi @Yette...
An easy way to see how this works is to add the following line below line 5 in your code.
console.log("num changes to: ["+num+"] and "+"res is now: ["+res+"]");
-----------------------
- Explanation of Code:
-----------------------
1) The loop will run 3 times before num > 0 is false.
2) Each loop will prepend the result of num%2 to the value of res.
3) See notes below showing the state of num and res in each loop cycle.
Loop 1:
num starts as 6
res becomes "0" => 6%2 + ""
num becomes 3 => Math.floor(6/2)
Loop 2:
num starts as 3
res becomes "10" => 3%2 + "0"
num becomes 1 => Math.floor(3/2)
Loop 3:
num starts as 1
res becomes "110" => 1%2 + "10"
num becomes 0 => Math.floor(1/2)
Now that num is 0, the loop will break and res is "110".
NOTE: This is the result of string concatenation, not arithmetic operations.
+ 2
// Created by Yette
function bin(num){
console.info(num);
var res = "";
while(num > 0){
res = num % 2 + res;
console.info(res);
num = Math.floor(num/2);
console.info(num);
}
console.info(res);
return res;
}
console.log(bin(6));
If you log the data as you go it helps a bit. Also confirms David Carroll's findings above.
+ 1
Oh OK
Now i understand,
Thank you both
0
No problem. Good luck :)