+ 2

Why output 110?

function bin(num) { var res=""; while(num>0) { res=num%2+res; num=Math.floor(num/2); } return res; } document.write(bin(6)); https://code.sololearn.com/W2zG4qt1DHSU/?ref=app So 6%2 is 0 plus "" is still zero, so why starts the outcome with 1? Shouldn't it be 011 or is the output of a function always written from right to left? 🤔

29th Apr 2018, 5:10 AM
Miro
Miro - avatar
1 Resposta
+ 3
@miro in the while loop you have res=num%2+res not res+=num%2+res #loop1 res=6%2+"" res=0 #loop2 res=3%2+"0" res=10 #loop3 res=1%2+"10" res=110
29th Apr 2018, 6:14 AM
᠌᠌Code X
᠌᠌Code X - avatar