+ 9
What is the difference between y=""; y=x%2+y; x=Math.floor(x/2); and y+=x%2
function z(x) { var y=""; while (x>0){ y = x%2 + y; x = Math.floor ( x/2); } return y} I cant understand how this function outputs the binary code of x. if I write first way it outputs 1010 for x=10: if the second way it outfuts 0101. how it happens?
2 Answers
+ 5
They are exactly opposed:
y = x%2 + y;
y+=x%2; is equals to y= y + x%2
BUT you handling strings then order is important here (differently by numbere where x+y and y+x get same result)
If you have asking why you have handling string, well when you add a string with another type var this var is converted to string for make operation
0
it will ofcource give binary as the method is to get binary is get the remainder of number by moduling 2 and after divide by 2 until num==0.. there is no need of Math.floor directly divide /x/2