Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reverse a negative integer in javascript?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading