Skip to content

Commit 3d3241c

Browse files
committed
solve aylei#9
1 parent 548ab66 commit 3d3241c

File tree

1 file changed

+52
-25
lines changed

1 file changed

+52
-25
lines changed

Diff for: src/n0009_palindrome_number.rs

+52-25
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
/**
2-
* [9] Palindrome Number
3-
*
1+
/**
2+
* [9] Palindrome Number
3+
*
44
* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
55
*
66
* Example 1:
@@ -29,25 +29,52 @@
2929
* Follow up:
3030
*
3131
* Coud you solve it without converting the integer to a string?
32-
*
33-
*/
34-
pub struct Solution {}
35-
36-
// submission codes start here
37-
38-
impl Solution {
39-
pub fn is_palindrome(x: i32) -> bool {
40-
41-
}
42-
}
43-
44-
// submission codes end
45-
46-
#[cfg(test)]
47-
mod tests {
48-
use super::*;
49-
50-
#[test]
51-
fn test_9() {
52-
}
53-
}
32+
*
33+
*/
34+
pub struct Solution {}
35+
36+
// submission codes start here
37+
38+
// not optimal, we only have to revert half of the string
39+
impl Solution {
40+
pub fn is_palindrome(x: i32) -> bool {
41+
if x < 0 { return false }
42+
let mut digits: Vec<i32> = Vec::new();
43+
let mut input = x;
44+
while input != 0 {
45+
digits.push(input % 10);
46+
input = input / 10;
47+
}
48+
let len = digits.len();
49+
// handle one digit
50+
if len < 2 { return true }
51+
// handle end with 0
52+
if digits[0] == 0 { return false }
53+
let mut i = 0;
54+
while i < len / 2 {
55+
if digits[i] != digits[len - 1 - i] {
56+
return false
57+
}
58+
i += 1;
59+
}
60+
true
61+
}
62+
}
63+
64+
// submission codes end
65+
66+
#[cfg(test)]
67+
mod tests {
68+
use super::*;
69+
70+
#[test]
71+
fn test_9() {
72+
assert_eq!(Solution::is_palindrome(-32), false);
73+
assert_eq!(Solution::is_palindrome(10), false);
74+
assert_eq!(Solution::is_palindrome(0), true);
75+
assert_eq!(Solution::is_palindrome(9), true);
76+
assert_eq!(Solution::is_palindrome(121), true);
77+
assert_eq!(Solution::is_palindrome(2222), true);
78+
assert_eq!(Solution::is_palindrome(11222211), true);
79+
}
80+
}

0 commit comments

Comments
 (0)