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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution {
func reverse(_ x: Int) -> Int {
let sign = x >= 0 ? 1 : -1
var str = String(sign * x)
str = String(str.reversed())
if( sign * Int(str)! > Int32.max || sign * Int(str)! < Int32.min) {
return 0
}
return sign * Int(str)!
}
}
Reverse Integer
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 題目:7. Reverse Integer 注意這里如果y是int,那么 Integer.MAX_VALUE/10...
- 1.Reverse digits of an integer. Example1: x = 123, return...
- Reverse digits of an integer. Example1: x = 123, return 3...