Leetcode Practice
LC 7. Reverse Integer
- Last updated
- Reading time
- 1 min read
The problem
Solution
function reverse(x: number): number {
let reverse = 0
let sign = x < 0 ? -1 : 1
x = Math.abs(x)
let num = x
let reverseExp = 0
for (let i = x.toString().length - 1; i >= 0; i--) {
const digit = Math.floor(num / 10 ** i)
reverse += digit * 10 ** reverseExp
num -= digit * 10 ** i
reverseExp++
}
const answer = sign * reverse
if ((-2) ** 31 > answer || answer > 2 ** 31) {
return 0
}
return answer
}