Skip to content

Commit 581442b

Browse files
committed
Reverse integer.
1 parent 88d1ab9 commit 581442b

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
3+
4+
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
5+
6+
 
7+
8+
Example 1:
9+
Input: x = 123
10+
Output: 321
11+
12+
Example 2:
13+
Input: x = -123
14+
Output: -321
15+
16+
Example 3:
17+
Input: x = 120
18+
Output: 21
19+
 
20+
21+
Constraints:
22+
- -231 <= x <= 231 - 1
23+
*/
24+
class Solution {
25+
func reverse(_ x: Int) -> Int {
26+
let str = "\(abs(x))"
27+
var i = str.count - 1
28+
var res = ""
29+
while i >= 0 {
30+
let e = str[str.index(str.startIndex, offsetBy: i)]
31+
res.append(e)
32+
i -= 1
33+
}
34+
35+
if let res = Int(res) {
36+
if x > 0 {
37+
return res >= 2147483647 ? 0 : res
38+
} else {
39+
return -res <= -2147483648 ? 0 : -res
40+
}
41+
} else {
42+
return 0
43+
}
44+
}
45+
}
46+
47+
let s = Solution()
48+
let r = s.reverse(-2147483648)
49+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/7.Reverse Integer.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,5 @@
109109
2. [Longest Substring Without Repeating Characters](https://github.com/recherst/leetcode-algtorithm/blob/main/Medium/3.Longest%20Substring%20Without%20Repeating%20Characters.playground/Contents.swift)
110110
3. [Longest Palindromic Substring](https://github.com/recherst/leetcode-algtorithm/blob/main/Medium/5.Longest%20Palindromic%20Substring.playground/Contents.swift)
111111
4. [ZigZag Conversion](https://github.com/recherst/leetcode-algtorithm/blob/main/Medium/6.ZigZag%20Conversion.playground/Contents.swift)
112+
5. [Reverse Integer](https://github.com/recherst/leetcode-algtorithm/blob/main/Medium/7.Reverse%20Integer.playground/Contents.swift)
113+

0 commit comments

Comments
 (0)