Reversing an integer by using Math.sign()
I recently learned how to use Math.sign from “The Coding Interview Bootcamp: Algorithms + Data Structures” and I believe it’s useful for many cases depending on how you want to implement it into your code. Below is one example of how to use Math.sign().
Here is the problem that need to solve:
--- Directions
Given an integer, return an integer that is the reverse
ordering of numbers.--- Examples
reverseInt(-15) === -51
Ideally to solve this problem, one needs to change the integer to string by using function toString() and then split() and changing string to array. This allows for the use of reverse function to reverse the numbers by using reverse(). Next, one can use function join() to combined all of the elements in an array. So, all of these steps allow one to reverse the given array. Code should be as follows:
This results in 15- but the desired result is -15, so another step is still needed. String 15- needs to be changed to integer.
As you can see, the result of variable reversed = 15- and after we converted to integer by using function parseInt() the result was 15 . Now it’s time to handle negative and positive numbers. How can this number be made negative? One has to create the logic to handle the negative numbers. If n is less than 0, a negative number needs to be added. Here is how to implement Math.sign() method. Math.sign returns +1 when positive integers are used, returns -1 when negative integers are used, and zero remains the same.
The
Math.sign()
function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed intoMath.sign()
is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned.
In this case, one multiples Math.sign(n) to get result -1 as follows:
Tada! we got the desired output! I hope this was helpful and you are able to implement this function into your coding.
Resources
- The Coding Interview Bootcamp: Algorithms + Data Structures
- Documentation: toString()
- Documentation: split()
- Documentation: reverse()
- Documentation: join()
- Documentation: Math.sign()
- Documentation: parseInt()