-
Notifications
You must be signed in to change notification settings - Fork 0
/
q7_reverse_integer.rs
50 lines (37 loc) · 996 Bytes
/
q7_reverse_integer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*!
[7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)
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 `[-2^31, 2^31 - 1]`, then return 0.
Example 1:
```html
Input: 123
Output: 321
```
Example 2:
```html
Input: -123
Output: -321
```
Example 3:
```html
Input: 120
Output: 21
```
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/
fn reverse(x: i32) -> i32 {
let mut new_str = String::new();
for (_, c) in x.abs().to_string().char_indices() {
new_str.insert(0, c);
}
if x < 0 {
new_str.insert(0, '-');
}
new_str.parse::<i32>().unwrap_or(0)
}
#[test]
fn q7_test() {
assert_eq!(reverse(123), 321);
assert_eq!(reverse(87654321), 12345678);
}