+ 1

How to reverse a number in JS

I've already searched around in the Q/A answers, but I couldn't find it, can anyone please help me?

2nd Apr 2018, 9:16 PM
Roel
Roel - avatar
4 ответов
+ 3
you can do that in two ways. The string way. and the mathematical way. the string way is this: function reverseNum(num){ var num_func = num.toString(); var reverseNumber =""; for(var x=num_func.length-1;x>=0;x--){ reverseNumber+=num_func[x]; } return reverseNumber; } the math way is this: function reverseNum(num){ var y=0; while(num>0){ y*=10; y+=num%10; num= Math.floor(num/10) } return y; }
2nd Apr 2018, 9:42 PM
Tomer Sim
Tomer Sim - avatar
+ 2
How is this shorter then writing reverseNum? anyway, You're using functions without knowing how they work.
2nd Apr 2018, 9:55 PM
Tomer Sim
Tomer Sim - avatar
0
Thanks, but I've got this from a friend document.write(t.split('').reverse().join('')) This is probably the string way, but it works a little smaller for large codes where I have to use it over 20 times
2nd Apr 2018, 9:45 PM
Roel
Roel - avatar
0
Sorry, I didn't read your answer very well, I thought I had to put the whole code every time
2nd Apr 2018, 9:57 PM
Roel
Roel - avatar