[removed] How to reverse a number?

前端 未结 10 935
余生分开走
余生分开走 2020-11-29 11:54

Below is my source code to reverse (as in mirror) the given number. I need to reverse the number using reverse method of arrays.

var a = prompt(\"Enter a va         


        
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 12:24

    I was recently asked how to solve this problem and this was my initial solution:


    The desired output: 123 => 321, -15 => -51, 500 => 5

    function revInt(num) {
    // Use toString() to convert it into a String
    // Use the split() method to return a new array: -123 => ['-', '1','2','3']
    // Use the reverse() method to reverse the new created array: ['-', '1','2','3'] => ['3','2','1','-'];
    // Use the join() method to join all elements of the array into a string
      let val = num.toString().split('').reverse().join('');
        // If the entered number was negative, then that '-' would be the last character in
       //  our newly created String, but we don't want that, instead what we want is
      //  for it to be the first one. So, this was the solution from the top of my head.
    
    // The endsWith() method determines whether a string ends with the characters of a specified string
      if (val.endsWith('-')) {
        val = '-' + val;
          return parseInt(val);
      }
          return parseInt(val);
    }
    
    console.log(revInt(-123));


    A way better solution:

    After I gave it some more thought, I came up with the following:

       // Here we're converting the result of the same functions used in the above example to 
    // an Integer and multiplying it by the value returned from the Math.sign() function.
    
    // NOTE: The Math.sign() function returns either a positive or negative +/- 1, 
    // indicating the sign of a number passed into the argument.   
    
    function reverseInt(n) {
          return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
    }
    
    console.log(reverseInt(-123));

    NOTE: The 2nd solution is much more straightforward, IMHO

提交回复
热议问题