7. Reverse Integer Medium

@problem@discussion
#Math



1/**
2 * [7] Reverse Integer
3 *
4 * Given a signed 32-bit integer x, return x with its digits reversed. If reversing x
5 * causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1],
6 * then return 0.
7 * Assume the environment does not allow you to store 64-bit integers (signed or 
8 * unsigned).
9 *  
10 * Example 1:
11 * Input: x = 123
12 * Output: 321
13 * Example 2:
14 * Input: x = -123
15 * Output: -321
16 * Example 3:
17 * Input: x = 120
18 * Output: 21
19 * Example 4:
20 * Input: x = 0
21 * Output: 0
22 *  
23 * Constraints:
24 * 
25 * -2^31 <= x <= 2^31 - 1
26 * 
27 */
28pub struct Solution {}
29
30// problem: https://leetcode.com/problems/reverse-integer/
31// discuss: https://leetcode.com/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34
35impl Solution {
36    pub fn reverse(x: i32) -> i32 {
37        let r = Self::reverse_64(x as i64);
38        if r > i32::MAX as i64 || r < i32::MIN as i64 {
39            0
40        } else {
41            r as i32
42        }
43    }
44
45    fn reverse_64(x: i64) -> i64 {
46        if x.is_negative() {
47            return -Self::reverse_64(-x);
48        }
49
50        let mut r = x;
51        let mut ans = 0;
52        while r > 0 {
53            ans = 10 * ans + r % 10;
54            r /= 10;
55        }
56
57        ans
58    }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn test_7() {
69        assert_eq!(Solution::reverse(123), 321);
70        assert_eq!(Solution::reverse(1), 1);
71        assert_eq!(Solution::reverse(-123), -321);
72        assert_eq!(Solution::reverse(i32::MAX), 0);
73    }
74}
75


Back
© 2025 bowen.ge All Rights Reserved.