# 문제
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
# 풀이
- 자릿수 하나씩 돌면서 결과값에 더해주기
- 32비트 정수형을 넘어서면 안되므로
Int.max
와 비교
class Solution {
func reverse(_ x: Int) -> Int {
var array: [Int] = []
var result = 0
for char in String(abs(x)) {
let value = Int(String(char))!
array.append(value)
}
for (index, i) in array.enumerated() {
let tens = Int(pow(Double(10), Double(index)))
result += tens * i
if result > Int32.max {
return 0
}
}
return x < 0 ? -result : result
}
}