9. Palindrome Number Easy

@problem@discussion
#Math



1/**
2 * [9] Palindrome Number
3 *
4 * Given an integer x, return true if x is palindrome integer.
5 * An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
6 *  
7 * Example 1:
8 * 
9 * Input: x = 121
10 * Output: true
11 * 
12 * Example 2:
13 * 
14 * Input: x = -121
15 * Output: false
16 * Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
17 * 
18 * Example 3:
19 * 
20 * Input: x = 10
21 * Output: false
22 * Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
23 * 
24 * Example 4:
25 * 
26 * Input: x = -101
27 * Output: false
28 * 
29 *  
30 * Constraints:
31 * 
32 * -2^31 <= x <= 2^31 - 1
33 * 
34 *  
35 * Follow up: Could you solve it without converting the integer to a string?
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/palindrome-number/
40// discuss: https://leetcode.com/problems/palindrome-number/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45    pub fn is_palindrome(x: i32) -> bool {
46        if x < 0 {
47            return false;
48        }
49
50        x as i64 == Self::reverse_64(x as i64)
51    }
52
53    fn reverse_64(x: i64) -> i64 {
54        if x.is_negative() {
55            return -Self::reverse_64(-x);
56        }
57
58        let mut r = x;
59        let mut ans = 0;
60        while r > 0 {
61            ans = 10 * ans + r % 10;
62            r /= 10;
63        }
64
65        ans
66    }
67}
68
69// submission codes end
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn test_9() {
77        assert!(Solution::is_palindrome(121));
78        assert!(!Solution::is_palindrome(-121));
79        assert!(!Solution::is_palindrome(321));
80        assert!(!Solution::is_palindrome(i32::MAX));
81    }
82}
83


Back
© 2025 bowen.ge All Rights Reserved.