What is the output of this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

What is the output of this code?

function tobin(num) { var res=""; while (num>0){ res=num%2+res; num=Math.floor(num/2); } return res; } document.write(tobin(4)); output: 100. why?

28th Jun 2019, 12:58 PM
Анна
2 Answers
+ 4
thank you so much, Airree
28th Jun 2019, 1:44 PM
Анна
+ 3
It basically turns a decimal number to a binary number. You can run through everything: res = num % 2 + res //4 % 2 = 0, so res = 0 num = Math.floor(num / 2) // 4 / 2 = 2, num = 2 //next iteration, num is bigger than 0 res = num % 2 + res //2 % 2 = 0, so res = 00 num = Math.floor(num / 2) //2 / 2 = 1, num is 1 //next iteration, num is bigger than 0 res = num % 2 + res //1 % 2 = 1, so res = 100 num = Math.floor(num / 2) //1 / 2 = 0.5, floor of 0.5 is 0, num = 0 //loop stops since num is 0
28th Jun 2019, 1:06 PM
Airree
Airree - avatar