'Reverse a number' function Problem description:

Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: \$[−2^{31},  2^{31} − 1]\$. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My solution:


var reverse = function(x) {
    temp = (x &lt; 0) ? -1 : 1;
    x = x * temp;
    let res = x % 10;
    while(x &gt; 9) {
        x = (x - x % 10) / 10;
        res = 10 * res + x % 10;
    };
    res = ((res &lt; 2147483648) &amp;&amp; (res &gt;= -2147483648)) ? res : 0;
    return res * temp;
};

console.log(reverse(-321));
console.log(reverse(1534236469));



Test:
Input #1: -321
Expected #1: -123

Input #2: 1534236469
Expected #2: 0

Test summmary:
Solution accepted
Runtime: 88ms

Question: Is there a way to make this function less complex, maybe also improving its runtime?
A simple and clear approach would be to take an array of characters of the number, and reverse the array:


const reverse = function(inputNum) {
    const result = Math.sign(inputNum) * String(Math.abs(inputNum))
      .split('')
      .reverse()
      .join('');
    return result &lt; -2147483648 || result &gt; 2147483647 ? 0 : result;
};
console.log(reverse(-321));
console.log(reverse(1534236469));



The runtime is a little bit higher (92ms, not sure how precisely reliable the measurements are on LeetCode, they seemed all over the place), but in the vast majority of real-world situations, to write strong and maintainable code, one should first optimize clarity and readability, and then if the whole app isn't running as fast as would be ideal, run a performance test to identify bottlenecks and work on those particular bottlenecks.
Note the use of Math.sign to determine whether the number is positive or negative - it'll return -1 if the number is negative, and 1 if the number is positive, so it's probably a bit more appropriate for the situation.
Another approach without creating an intermediate array would be
let res = '';
for (let i = inputStr.length - 1; i &gt;= 0; i--) res += inputStr[i];

With regards to your code:
Always declare your variables You're implicitly creating a global variable temp. Implicit creation of global variables will cause odd bugs when a function gets called when it's already in the process of running. Consider using a linter or strict mode or both to avoid these sorts of mistakes. (When declaring variables, prefer const, or use let when it needs to be reassigned.) On a similar note, your reverse function should be declared with const (not var).
Give variables meaningful names An argument named x and a variable named temp aren't very informative at a glance. How about calling them inputNum and sign instead?