Skip to content

Commit

Permalink
Add solution for Reverse Integer
Browse files Browse the repository at this point in the history
  • Loading branch information
Charlene Jiang committed Jul 20, 2016
1 parent 6332129 commit 97e7251
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Math/ReverseInteger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Question Link: https://leetcode.com/problems/reverse-integer/
* Primary idea: Return 0 is the reversal number exceeds the Int32 range.
* Time Complexity: O(1)
*/

class Solution {
func reverse(x: Int) -> Int {
if x < 0 {
return 0 - reverse(0 - x)
}

var carry = 1
var ret = 0
for c in String(x).characters {
let someString = String(c)
if let someInt = Int(someString) {
ret += someInt * carry
carry *= 10
}
}

if ret > Int(Int32.max) || ret < Int(Int32.min) {
return 0
}

return ret
}
}

0 comments on commit 97e7251

Please sign in to comment.