Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

反转数字字符串

Open Twlig opened this issue 3 years ago • 2 comments

Twlig avatar Apr 13 '22 13:04 Twlig

function reverseNum(num) {
      if(!num) return num; 
      if(num < 0) Number('-' + num.toString().slice(1).reverse());
      return Number(num.toString().reverse());
}

TheFirstSunday avatar Apr 18 '22 08:04 TheFirstSunday

const max = Math.pow(2, 31) - 1;
const min = -Math.pow(2, 31);

const reverseNum = function(x) {

    var y = 0;
    while(x !== 0) {
        y = 10 * y + x % 10;
        x = ~~(x/10);
    }
    if (y > max) return 0;
    if (y < min) return 0;
    return y;
};

TheFirstSunday avatar Apr 18 '22 08:04 TheFirstSunday