반응형
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 [-231, 231 - 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
Constraints:
- -231 <= x <= 231 - 1
Solution(Kotlin):
- 부호를 체크하여 뒤집어준다.
- NumberFormatException가 발생하는 곳을 체크해준다.
1. Int의 범위값을 넘어가면 절대값을 나타내는 abs()함수가 작동하지 않으면서 부호'-'를 숫자로 바꾸는 과정에서NumberFormatException이 발생한다.
2. Int범위 값을 넘어가면 결과값 반환 시 toInt()함수에서 NumberFormatException가 발생한다.
import kotlin.math.abs
class Solution {
fun reverse(x: Int): Int {
return try {
val positive = (x > 0)
val r = abs(x).toString().map { it.toString().toInt() }.reversed()
var ans = ""
for (i in r.indices) ans += r[i]
if (positive) ans.toInt() else ans.toInt() * -1
} catch (e: NumberFormatException) {
0
}
}
}
반응형
댓글