Coding/LeetCode
[LeetCode/JavaScript] 7. Reverse Integer (medium)
성으니:)
2021. 9. 5. 08:12
문제
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
입출력
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Example 4:
Input: x = 0 Output: 0
제약
Constraints:
- -2^31 <= x <= 2^31 - 1
코드
var reverse = function(x) {
if(x>0) {
x = reverseStr(x);
}
else if(x<0) {
x = reverseStr(Math.abs(x));
x = -x;
}
if(x<Math.pow(-2, 31) || x>Math.pow(2, 31)-1) return 0
return x;
};
function reverseStr(num) {
return num.toString().split("").reverse().join().replaceAll(',', '');
}