Performance
Numbers
You can get a little more out of JS numbers if you force them to be 32 Bit Signed Integers. (Note this will depend on the JS engine. Works for V8 (chrome))
This is done by performing a bit wise operation on the number
Eg the double 2147483648 is converted to the uint32 -2147483648 by applying bit wise or zero (2147483648 | 0) === -2147483648
is true.
Integers are generally about 4-5% quicker than using Doubles.
As applying a bit-wise operator to a positive double < 2 ** 31 is the equivalent to Math.floor you can also gain some improvement by simplifying x = (x - x % 10) / 10;
to x = x / 10 | 0
. Saving a subtraction and a remainder per iteration.
Early exit
Approx 42% of reversed numbers will be out of range.
Thus there is also an opportunity for performance gain with an exit early.
We can check if the lowest digit is greater than 2 and number is greater than 1e9 and just return 0 if so thus not having to process a significant number of the 42% out of range values.
Use declared variables
You use the value temp
that you have not declared. That means it will be in global scope. Every step out of the current scope a variable is the slower the access to the variable.
If you declare temp
in the functions scope and use strict mode you will gain a significant performance boost.
Needless test
You can remove the test for < -2147483648 as the result will be positive until you revert the sign. Thus you can change the sign at the very last moment saving the need to check past the min int.
Rewrite is 3.5 times faster
The rewrite is 3.5 times quicker (for a random set of 32bit signed integers)
Though the source is a little longer it is well worth the performance gain
function reverse(num) {
"use strict";
const max = 0x80000000;
const sign = (num & max) ? -1 : 1;
num *= sign;
var res = num % 10;
if (num < 1e9 || res < 3) {
while (num > 9) {
num = num / 10 | 0;
res = res * 10 + (num % 10);
}
return res < max ? res * sign : 0;
}
return 0;
}