|
| 1 | +/** |
| 2 | + * [9] Palindrome Number |
| 3 | + * |
| 4 | + * Given an integer x, return true if x is a <span data-keyword="palindrome-integer">palindrome</span>, and false otherwise. |
| 5 | + * |
| 6 | + * <strong class="example">Example 1: |
| 7 | + * |
| 8 | + * Input: x = 121 |
| 9 | + * Output: true |
| 10 | + * Explanation: 121 reads as 121 from left to right and from right to left. |
| 11 | + * |
| 12 | + * <strong class="example">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 | + * <strong class="example">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 | + * |
| 25 | + * Constraints: |
| 26 | + * |
| 27 | + * -2^31 <= x <= 2^31 - 1 |
| 28 | + * |
| 29 | + * |
| 30 | + * Follow up: Could you solve it without converting the integer to a string? |
| 31 | + */ |
| 32 | +pub struct Solution {} |
| 33 | + |
| 34 | +// problem: https://leetcode.com/problems/palindrome-number/ |
| 35 | +// discuss: https://leetcode.com/problems/palindrome-number/discuss/?currentPage=1&orderBy=most_votes&query= |
| 36 | + |
| 37 | +// submission codes start here |
| 38 | + |
| 39 | +impl Solution { |
| 40 | + pub fn is_palindrome(x: i32) -> bool { |
| 41 | + fn make_palindrome(pre: i32, x: i32) -> i32 { |
| 42 | + if (x < 10) { |
| 43 | + return pre * 10 + x; |
| 44 | + } else { |
| 45 | + let d = x % 10; |
| 46 | + return make_palindrome(pre * 10 + d, x / 10); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if x < 0 { |
| 51 | + return false; |
| 52 | + } else { |
| 53 | + return x == make_palindrome(0, x); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// submission codes end |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::*; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn test_1() { |
| 66 | + let input = 123; |
| 67 | + let res = Solution::is_palindrome(input); |
| 68 | + assert_eq!(false, res); |
| 69 | + } |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_2() { |
| 73 | + let input = 1; |
| 74 | + let res = Solution::is_palindrome(input); |
| 75 | + assert_eq!(true, res); |
| 76 | + } |
| 77 | + |
| 78 | + #[test] |
| 79 | + fn test_3() { |
| 80 | + let input = 313; |
| 81 | + let res = Solution::is_palindrome(input); |
| 82 | + assert_eq!(true, res); |
| 83 | + } |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn test_4() { |
| 87 | + let input = -123; |
| 88 | + let res = Solution::is_palindrome(input); |
| 89 | + assert_eq!(false, res); |
| 90 | + } |
| 91 | +} |
0 commit comments