Palindromic Numbers

-

A palindromic number is a number whose digits are a palindrome. An example would be 8118 or 101.

Using strings

To test whether or not a number is a palindrome, one way is to convert it to a string and check whether or not that string is a palindrome.

fn is_palindrome(n: u32) -> bool {
    n.to_string() == n.to_string().chars().rev().collect::<String>()
}

A more mathematical approach

However, there is another way. I’ve been taking the Brilliant course on Number Theory and it got me thinking about a more numerical solution.

Looking at the number 8118, it can be decomposed into $$8118 = 8 * 1000 + 1 * 100 + 1 * 10 + 8 * 1$$

We can use that insight to then compose the number into digits. We can take our number modulo 10, and put the remainder into a vector. We then divide our number by 10 and repeat the process until our number is 0.

let mut digits: Vec<u32> = Vec::new();

while number_to_divide != 0 {
    digits.push(number_to_divide % 10);
    number_to_divide /= 10;
}

From there, all we have to do is run a traditional palindrome algorithm to see whether or not the elements of that vector are a palindrome.

for i in 0..digits.len()/2 {
        if digits[i] != digits[digits.len() - i - 1] {
            return false;
        } 
    }
true

It’s a simple problem that’s fun to solve in multiple ways.