Reverse decimal digits in javascript

后端 未结 14 838
灰色年华
灰色年华 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: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;
    }
    

提交回复
热议问题