File tree 3 files changed +82
-1
lines changed
3 files changed +82
-1
lines changed Original file line number Diff line number Diff line change 1
- mod p0004_median_of_two_sorted_arrays;
1
+ mod p0004_median_of_two_sorted_arrays;
Original file line number Diff line number Diff line change @@ -5,3 +5,4 @@ mod s0005_longest_palindromic_substring;
5
5
mod s0006_zigzag_conversion;
6
6
mod s0007_reverse_integer;
7
7
mod s0008_string_to_integer_atoi;
8
+ mod s0009_palindrome_number;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * [9] 回文数
3
+ *
4
+ * 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
5
+ * 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
6
+ *
7
+ * 例如,121 是回文,而 123 不是。
8
+ *
9
+ *
10
+ * 示例 1:
11
+ *
12
+ * 输入:x = 121
13
+ * 输出:true
14
+ *
15
+ * 示例 2:
16
+ *
17
+ * 输入:x = -121
18
+ * 输出:false
19
+ * 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
20
+ *
21
+ * 示例 3:
22
+ *
23
+ * 输入:x = 10
24
+ * 输出:false
25
+ * 解释:从右向左读, 为 01 。因此它不是一个回文数。
26
+ *
27
+ *
28
+ * 提示:
29
+ *
30
+ * -2^31 <= x <= 2^31 - 1
31
+ *
32
+ *
33
+ * 进阶:你能不将整数转为字符串来解决这个问题吗?
34
+ *
35
+ */
36
+ pub struct Solution { }
37
+
38
+ // problem: https://leetcode.cn/problems/palindrome-number/
39
+ // discuss: https://leetcode.cn/problems/palindrome-number/discuss/?currentPage=1&orderBy=most_votes&query=
40
+
41
+ // submission codes start here
42
+
43
+ impl Solution {
44
+ pub fn is_palindrome ( x : i32 ) -> bool {
45
+ if x < 0 {
46
+ return false ;
47
+ } else if x == 0 {
48
+ return true ;
49
+ }
50
+ let mut y: i32 = x;
51
+ let mut t: i32 = 0 ;
52
+ while y > 0 {
53
+ if t. checked_mul ( 10 ) . is_none ( ) {
54
+ return false ;
55
+ }
56
+ t = t * 10 ;
57
+ if t. checked_add ( y % 10 ) . is_none ( ) {
58
+ return false ;
59
+ }
60
+ t = t + y % 10 ;
61
+ y = y / 10 ;
62
+ }
63
+ t == x
64
+ }
65
+ }
66
+
67
+ // submission codes end
68
+
69
+ #[ cfg( test) ]
70
+ mod tests {
71
+ use super :: * ;
72
+
73
+ #[ test]
74
+ fn test_9 ( ) {
75
+ assert_eq ! ( Solution :: is_palindrome( 123 ) , false ) ;
76
+ assert_eq ! ( Solution :: is_palindrome( 121 ) , true ) ;
77
+ assert_eq ! ( Solution :: is_palindrome( 1 ) , true ) ;
78
+ assert_eq ! ( Solution :: is_palindrome( -121 ) , false ) ;
79
+ }
80
+ }
You can’t perform that action at this time.
0 commit comments