Reverse An Integer
Problem Explanation
We should create a function that takes an integer and returns the integer’s order of numbers in reverse. We should also make sure that negative integers remain negative.
Relevant Links
Hints
Hint 1
Although we need to return a number, we can convert a number into a string, perform some operations, and then convert back into a number and return the value…
Hint 2
With the help of Math.sign, we can ensure negative numbers remain negative by multiplying the function’s return value with the sign of the original number.
Solutions
Solution 1 (Click to Show/Hide)
js
function reverseInt(n) {
const rev = n
.toString()
.split('')
.reverse()
.join('')
return parseInt(rev) * Math.sign(n)
}
Code Explanation
- Create a new variable and set it to n (our original integer)
- Chain .toString() to n in order to first convert the number into a string.
- Split the string with the method .split("") into an array of substrings to access each unique integer.
- We can now reverse the array of numbers with .reverse().
- Switch the array back into a string using .join(’’) method.
- Now return the reversed string and convert it back to an integer with parseInt().
- Finally, multiply the resulting number by the sign of the function’s original number using Math.sign() to make sure negative numbers are returned in their negative form.