So I came across a problem "How to reverse an integer in javascript?" I successfully managed to reverse the positive numbers for eg if I enter 123 then I get the output 321 but on the hand, if I am trying some negative number like -123 then I get 0 as the output. How can I solve this issue and get output as -321?
var reverse = function(x){
let a = 0;
while(x>0){
a = a * 10 + x%10;
// 0 = 0 *10 + 123%10 = 3
// a=3
// 0 = 0 *10 + 12%10 = 2
// a=2
// 0 = 0*10 + 1%10 = 1
// a=1
x = Math.floor(x/10)
// x = 123/10 = 12
// x = 12/10 =1
}
console.log(a);
return a;
}
var x = -123;
reverse(x)
while (x > 0)will not really work well ifxis negative. (note that the reverse of a negative x is simply-reverse(-x))abson top of your input and deal with the negative sign at the end