~janbaudisch/euler-rs

a5794411d1d1deb0becddc1861802f6faf715b5b — Jan Baudisch 5 years ago 9e1a7f6
common: add palindrome
2 files changed, 32 insertions(+), 0 deletions(-)

M common/src/math/mod.rs
A common/src/math/palindrome.rs
M common/src/math/mod.rs => common/src/math/mod.rs +2 -0
@@ 1,7 1,9 @@
mod factorial;
mod fibonacci;
mod palindrome;
mod prime;

pub use factorial::*;
pub use fibonacci::*;
pub use palindrome::*;
pub use prime::*;

A common/src/math/palindrome.rs => common/src/math/palindrome.rs +30 -0
@@ 0,0 1,30 @@
pub trait IsPalindrome {
    fn is_palindrome(self) -> bool;
}

macro_rules! impl_is_palindrome {
    ($type: ident) => {
        impl IsPalindrome for $type {
            fn is_palindrome(self) -> bool {
                let digits = self.to_string().chars().collect::<Vec<char>>();

                let (left, right) = if &digits.len() % 2 == 0 {
                    digits.split_at(digits.len() / 2)
                } else {
                    digits.split_at((digits.len() - 1) / 2)
                };

                let mut right = right.to_vec();
                right.reverse();

                left == right.as_slice()
            }
        }
    };
}

impl_is_palindrome!(u8);
impl_is_palindrome!(u16);
impl_is_palindrome!(u32);
impl_is_palindrome!(u64);
impl_is_palindrome!(u128);