-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_integer.rs
95 lines (79 loc) · 1.99 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/// Given a signed 32-bit integer `x`, return `x` with its digits reversed. If
/// reversing `x` causes the value to go outside the 32-bit integer range
/// `[-2^31, 2^31 - 1]`, then return `0`.
///
/// Assume the environment does not allow you to store 64-bit integers (signed
/// or unsigned).
struct Solution;
impl Solution {
pub fn reverse(x: i32) -> i32 {
let mut result = 0;
if x != i32::MIN {
let is_negative = x < 0;
let mut value = x;
if is_negative {
value *= -1;
}
while value > 0 {
let digit = value % 10;
value /= 10;
if result > i32::MAX / 10 {
result = 0;
break;
} else {
result *= 10;
}
if result > i32::MAX - digit {
result = 0;
break;
} else {
result += digit;
}
}
if is_negative {
result *= -1;
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let x = 123;
let result = Solution::reverse(x);
assert_eq!(result, 321);
}
#[test]
fn example_2() {
let x = -123;
let result = Solution::reverse(x);
assert_eq!(result, -321);
}
#[test]
fn example_3() {
let x = 120;
let result = Solution::reverse(x);
assert_eq!(result, 21);
}
#[test]
fn same_reversed() {
let x = 1000000001;
let result = Solution::reverse(x);
assert_eq!(result, x);
}
#[test]
fn minimum() {
let x = i32::MIN;
let result = Solution::reverse(x);
assert_eq!(result, 0);
}
#[test]
fn maximum() {
let x = i32::MAX;
let result = Solution::reverse(x);
assert_eq!(result, 0);
}
}