Integer Reversal

PHOTO EMBED

Wed Sep 15 2021 13:34:13 GMT+0000 (Coordinated Universal Time)

Saved by @sangelici94 #javascript #strings #reversal #integers

// SOLUTION 1 - MY SOLUTION (RUNTIME - 92MS, MEMORY - 40.7MB)
var reverse = function(x) {
    // set variable that converts integer to a string, splits into an arr, reverses arr, and rejoins into a string
    const temp = x.toString().split("").reverse().join("");
    // converts string back into an integer
    let reversedNum = parseInt(temp);
    
    // using original argument, check if reversed number needs to be a positive or negative value
    if (Math.sign(x) === -1) reversedNum = reversedNum * -1
    
    // check to see if reversed integer fits within listed 32-bit contraint
    if (Math.pow(-2, 31) > reversedNum || reversedNum > Math.pow(2, 31)) return 0;
    else return reversedNum  
};

// SOLUTION 2 (BEST RUNTIME - 60MS)
var reverse = function(x) {
    const limit = 2147483648;
    const reversedNum = parseFloat(x.toString().split("").reverse().join(""))
    return reversedNum > limit ? 0 : reversedNum * Math.sign(x);
};

// SOLUTION 3 (RUNTIME - 60MS)
var reverse = function(x) {
    const sign = x < 0 ? -1 : 1;
    const positiveX = x * sign;
    const y = parseInt(positiveX.toString().split('').reverse().join('')) * sign;
    const absoluteY = y * sign;
    
  //0x7FFFFFFF is a number in hexadecimal (2,147,483,647 in decimal) that represents the maximum positive value for a 32-bit signed binary integer
    return absoluteY <= (y < 0 ? 0x80000000 : 0x7FFFFFFF) ? y : 0;
};
content_copyCOPY

Solutions to reverse an integer. Solutions include converting integer to a string to reverse the order and then reconvert back into a number, checks for the sign value of the x argument for the function and adjusting the reversed value to match, and a final check to make sure the reversed value fits within a 32-bit constraint (return 0 if it does not)

https://leetcode.com/submissions/detail/555353674/?from=explore&item_id=880