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)
>Solution :
Just Preserve the sign of an integer, like
var reverse = function(x){
let sign = x<0?-1:1;
let a = 0;
x=Math.abs(x);
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(sign*a);
return a;
}
var x = -123;
reverse(x)