LeetCode 7. Reverse Integer

May. 16, 2021

My initial solution for Reverse Integer problem:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {

    let ans = '';
    if (x<0) {
        ans = '-';
        x*=-1;
    }

    str = x.toString();

    for (let i=str.length-1; i>=0; i--) {
        ans += str[i];
    }

    ans = parseInt(ans);
    if (ans>2**31-1 || ans<(-2)**31) {
        return 0;
    }
    return ans;
};

Results

Runtime: 104 ms, faster than 34.78% of JavaScript online submissions for Reverse Integer.

Memory Usage: 40.5 MB, less than 33.80% of JavaScript online submissions for Reverse Integer.

Optimized Version:

After looking at solution and transpiling it to JavaScript:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {

    const max = 2**31-1;
    const min = (-2)**31;
    let ans = 0;

    while (x != 0) {
        const pop = x%10;
        x = Math.trunc(x/10);
        if (ans > max/10) return 0;
        if (ans < min/10) return 0;

        ans = ans * 10 + pop;
    }

    return ans;
};

Optimized Results

Runtime: 92 ms, faster than 87.08% of JavaScript online submissions for Reverse Integer.

Memory Usage: 40.4 MB, less than 33.80% of JavaScript online submissions for Reverse Integer.