+ 1
Could You explain this answer?
res = 0; for(i=407;i>0;i=Math.floor(i/10)){ res= res*10+i%10;} document.write(res); answer is 704, why? I understand that i=Math.floor(i/10) is equal to 40.
2 Antworten
+ 2
before first loop ( intialisation ):
res == 0, i == 407 > 0 is true
first loop:
res == 0*10+407%10 == 7 ( division rest of 407 by 10 )
end first loop:
i == Math.floor(407/10) == 40 ( you was right here )
before second loop:
res == 7, i == 40 > 0 is true
second loop:
res == 7*10+40%10 == 70 ( division rest == 0, and times 10 make kind of shift to the left )
end second loop:
i == Math.floor(40/10) == 4
before third loop:
res == 70, i == 4 > 0 is true
third loop:
res == 70*10+4%10 == 704
end third loop:
i == Math.floor(4/10) == 0 > 0 is false... end of looping, write "704" which is the value of 'res" ^^
+ 1
thanks, now I got it.