Reverse decimal digits in javascript

后端 未结 14 841
灰色年华
灰色年华 2021-02-05 16:24

How do I reverse the digits of a number using bitwise?

input:

x = 123; 

output:

x = 321; 
相关标签:
14条回答
  • 2021-02-05 17:09

    That's not inverting bits; that's reversing the order of decimal digits, which is completely different. Here's one way:

    var x = 123;
    var y = 0;
    for(; x; x = Math.floor(x / 10)) {
        y *= 10;
        y += x % 10;
    }
    x = y;
    

    If you actually want to invert bits, it's:

    x = ~x;
    

    As a function:

    function reverse(n) {
        for(var r = 0; n; n = Math.floor(n / 10)) {
            r *= 10;
            r += n % 10;
        }
        return r;
    }
    
    0 讨论(0)
  • 2021-02-05 17:11

    If you wanted to make a simple reversal:

    var x = 123;
    var y = x.toString();
    var z = y.split("").reverse().join("");
    var aa = Number(z);
    document.write(aa);
    

    http://jsfiddle.net/jasongennaro/gV39e/

    0 讨论(0)
  • 2021-02-05 17:11
    <html>
    <script>
    
    function reverseInt(n){
    
            var r=0;
        while(n!=0){
            r*=10;
            r+=n%10;
            n=Math.floor(n/10);
    }
    return r;
    }
    
    
    </script>
    </html>
    
    0 讨论(0)
  • 2021-02-05 17:13

    Memory Usage: 35.3 MB, less than 100.00% of JavaScript online submissions for Reverse Integer on leetcode.com. Runtime: 80 ms, faster than 61.48% of JavaScript online submissions for Reverse Integer.

    Time complexity is O(log10(n)).

    function reverse(x) {
      let rev = 0;
      const isNegative = Math.sign(x) === -1;
      const isOverflow = n => n > 2**31;
      x = Math.abs(x);
    
      while (x) {
        let pop = x % 10;
        x = Math.floor(x / 10);
        rev = rev * 10 + pop;
    
        if (isOverflow(rev)) {
          return 0;
        } 
      }
    
      return isNegative ? rev * -1 : rev;
    }
    
    0 讨论(0)
  • 2021-02-05 17:15
    //reverse integer
    const revInt = (num)=>{
      //turn into string
      if(Math.sign(num)===1)
        return parseInt(num.toString().split('').reverse().join(''));
      else return -1*parseInt(num.toString().split('').reverse().join(''));
    }
    
    console.log(revInt(-501));
    
    0 讨论(0)
  • Reversing The Positive/ Negative Integer Number

    function reverseInt(n) {
     return parseInt(n.toString().split('').reverse().join()) * Math.sign(n)
    }
    

    If n is -5, then Math.sign(n)==> will return -1

    If n is 5, then Math.sign(n)==> will return 1

    0 讨论(0)
提交回复
热议问题