題目
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
翻譯
假設給定一個整數,範圍為 [−231, 231 − 1] 之間,請對它進行翻轉,如果輸入 -123 的時候就會變成 -321,如果輸入 120 的時候,前面的 0 應該自動去掉變成 21,那如果超過範圍的話就回傳 0 即可。
思維
因為這題是屬於簡單,所以將其轉成字串在透過 reverse 的方法就好,如果你覺得想挑戰一下,可以自行實作 reverse 的方法。
實作
fun reverse(x: Int): Int {
val result = Math.abs(x).toString().reversed()
return result.toIntOrNull()?.let {
it * if (x < 0) -1 else 1
} ?: 0
}