forked from WenchaoD/LeetCode_Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Charlene Jiang
committed
Jul 20, 2016
1 parent
6332129
commit 97e7251
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |