Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 883ba44

Browse files
committed
7. Reverse Integer
1 parent 977b9d9 commit 883ba44

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

7. Reverse Integer.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 7. Reverse Integer
2+
3+
### 2017-03-08
4+
5+
Reverse digits of an integer.
6+
7+
**Example1:** x = 123, return 321
8+
**Example2:** x = -123, return -321
9+
10+
[click to show spoilers.](https://leetcode.com/problems/reverse-integer/?tab=Description#)
11+
12+
**Have you thought about this?**Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
13+
14+
**Note:**
15+
The input is assumed to be a 32-bit signed integer. Your function should **return 0 when the reversed integer overflows**.
16+
17+
18+
19+
# Solution
20+
21+
```swift
22+
class Solution {
23+
func reverse(_ x: Int) -> Int {
24+
var c = abs(x)
25+
var r = 0
26+
let max = Int(Int32.max)
27+
while c != 0 {
28+
r = r * 10 + c % 10
29+
c = c / 10
30+
if r > max { return 0 }
31+
}
32+
return r * (x < 0 ? -1 : 1)
33+
}
34+
}
35+
```
36+

0 commit comments

Comments
 (0)