Reverse Integer
You're given a signed 32-bit integer x. Reverse the order of its digits and return the result. If reversing would push the value outside the signed 32-bit range, return 0 instead.
Input Format
Implement reverse(x). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
x = 123 Output
321 Example 2
Input
x = -123 Output
-321 Example 3
Input
x = 120 Output
21 Constraints
- -2^31 <= x <= 2^31 - 1
Test Cases (3)
Case 1
Args: [123]
Expected: 321
Case 2
Args: [-123]
Expected: -321
Case 3
Args: [120]
Expected: 21
Pop and Push Digits
function reverse(x) {
let result = 0;
while (x !== 0) {
result = result * 10 + x % 10;
x = Math.trunc(x / 10);
}
return result > 2**31 - 1 || result < -(2**31) ? 0 : result;
}Time: O(log x) | Space: O(1)
Saved in this browser only. Private to you.