Skip to content

Instantly share code, notes, and snippets.

@spurscho
Last active June 3, 2021 01:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spurscho/df557b8d6f7552e174fd13ee2f271d2a to your computer and use it in GitHub Desktop.
Save spurscho/df557b8d6f7552e174fd13ee2f271d2a to your computer and use it in GitHub Desktop.
class Solution {
func reverse(_ x: Int) -> Int {
let str: String = String(x)
let arr = str.reversed().filter{( $0 != ".")}
var result: Int
var resStr: String = ""
if x == -0 {
return 0
}
for i in 0 ..< arr.count {
resStr += "\(arr[i])"
}
if resStr[resStr.index(resStr.startIndex, offsetBy: resStr.count-1)] == "-" {
let range = resStr.startIndex ..< resStr.index(before: resStr.endIndex)
result = Int(resStr[range]) ?? 0
result = -result
} else {
result = Int(resStr) ?? 0
}
if result > Int32.max || result < Int32.min {
result = 0
}
return result ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment