Posting rust solutions in leetcode

I am new to programming and new to rust.
I came across leetcode.com and picked up problem #479. Largest Palindrome Product to practice.
I worked the solution in my computer and it worked just fine.
when i try to post in leetcode it throws an error.
I have my code in main function without calling any other functions.
in leetcode there is a predefined template as :

impl Solution {
    pub fn largest_palindrome(n: i32) -> i32 {
        
    }
}

how do i post my solution here in this leet code template above?

My Solution:
From the product of 2 n-digit numbers, find the largest palindrome number. where n is 1 <= n <= 8

fn main() {
    let n:u32 = 2;
    // match constraint for n: 1 <= n <= 8
    match n {
        1..=8 =>println!("'n' Witin constraint: 1 <= n <= 8"),
        _ => {println!("'n' Out-Of constraint: 1 <= n <= 8\nTry Again!"); return;}
    }
    let smallest_n_digit_num:i64 = 10i64.pow(n-1);
    let largest_n_digit_num:i64 = (10i64.pow(n))-1;
    'out: for factor_one in (smallest_n_digit_num..=largest_n_digit_num).rev() {
              for factor_two in (smallest_n_digit_num..=largest_n_digit_num).rev(){
                // here i nested for loop from largest number gradually to smallest
                // because i want to check from largest product to find largest palindrome
                if factor_two > factor_one {continue;} // This removes the redudancy in the product.
                let product:i64 = factor_one * factor_two; // gets product of 2 n-digit number
                /*
                // test println to check:
                //println!(factors: {factor_one} X {factor_two} = {product} :product.");
                */
                // now i will reverse the product
                let mut number = product; // new variable 'number' takes the value of 'product' variable.
                let mut reverse:i64 = 0; // new variable 'reverse' holds value of 0.
                while number !=0 {
                    // 'number%10' outputs the last digit of 'number' variable
                    // 'reverse = (reverse * 10) + number % 10' appends last digit from 'number' variable to 'reverse' variable
                    reverse = (reverse * 10) + number % 10;
                    // after catching the last digit of 'number' variable,
                    // remove the last digit from 'number' variable by: '(number-(number%10)) / 10'
                    // then update 'number' variable, 'number = (number-(number%10)) / 10'
                    number = (number-(number%10)) / 10;
                    // now second-last digit of product variable becomes last digit of number variable
                    // put this in loop until 'number' variable becomes 0 and 'reverse' variable become reverse number of 'product' variable.
                    }
                // now check for palindrome
                if reverse == product {
                    /*
                    // test println to check:
                    //println!("palindrome is: {product}. With factors: {factor_one} & {factor_two}");
                    // now we catch the largest palindrome product: which is product of its largest factors.
                    // because our factors range from largest to smallest,
                    // the first palindrome found will be the largest palindrome.
                    */
                        println!("Input: n = {n}\nOutput: {}",product % 1337);
                        println!("Explanation: {factor_one} x {factor_two} = {product}, {product} % 1337 = {}",product % 1337);                        
                        break 'out;                   
                    }
            }
        
    }
}

Am i missing something here? Sorry for being nuisance, if i am, it is not intended.
here is the question snip from leetcode:

Leetcode does make you post your answers in this weird format for Rust, and I believe their problems are just ported from some other default language and are often a poor fit for Rust. E.g. data structures you wouldn't necessarily use, sentinel values instead of Option or Result, etc.

In the rest of this post, I'm not going to check your code for correctness or even check the Leetcode problem for their exact requirements, and I'm not going to try submitting the end result, I'm just going to walk through how to "port" it to what I understand they're expecting:

  • An impl Solution with a particular function, as you've supplied
  • Inputs are arguments to said function (not things you hard code)
  • Outputs are returns from said function (not things you print)
  • Explanations are just in the problem statement for you to read, and not something you need to do (e.g. print) in your program

With those disclaimers out of the way, let's see how we might get your code into the Leetcode format.


They want something that looks like this:

impl Solution {
    pub fn largest_palindrome(n: i32) -> i32 {
        // Your Code Here
    }
}

I'm going to emulate this in the playground by adding this at the top, but it wouldn't be in your Leetcode submission:

struct Solution;
fn main() { dbg!(Solution::largest_palindrome(2)); }

In your code, you're

  • hardcoding the value instead of taking an argument
  • working with u32 and not i32
  • printing answers instead of returning them

Let's tackle each of those.


First, we replace this part:

fn main() {
    let n:u32 = 2;
    // match constraint for n: 1 <= n <= 8
    match n {
        1..=8 =>println!("'n' Witin constraint: 1 <= n <= 8"),
        _ => {println!("'n' Out-Of constraint: 1 <= n <= 8\nTry Again!"); return;}
    }

With something that takes an i32 and converts it if it makes sense

    pub fn largest_palindrome(input: i32) -> i32 {
        let n: u32 = match input {
            // If it's in this range we know the conversion must work
            1..=8 => input.try_into().unwrap(),
            // I'm just picking an arbitrary value to return here, I didn't look up
            // what Leetcode expects
            _ => return 1,
        };

And because we need a return value which you didn't have, I'm adding this at the bottom of the function for now, as a default return value:

        -1
    }

Now were in the right format, but only ever return 0 or -1, and you're still just printing things out.

The only time you do print out a solution is here:

                if reverse == product {
                    /*
                    // test println to check:
                    //println!("palindrome is: {product}. With factors: {factor_one} & {factor_two}");
                    // now we catch the largest palindrome product: which is product of its largest factors.
                    // because our factors range from largest to smallest,
                    // the first palindrome found will be the largest palindrome.
                     */
                    println!("Input: n = {n}\nOutput: {}", product % 1337);
                    println!(
                        "Explanation: {factor_one} x {factor_two} = {product}, {product} % 1337 = {}",
                        product % 1337
                    );
                    break 'out;
                }

So we just need to return the value instead:

                if reverse == product {
                    let output = product % 1337;
                    // mod 1337 will fit into an i32
                    return output.try_into().unwrap()
                }

Now it's working more like expected.

You can remove the now unused loop label to get rid of the warning. Clippy (under Tools, top right menu) does complain about anything after that, and here's the result.

The impl Solution block now looks like you said it should, and the code now takes and returns an i32 instead of printing answers with hard-coded inputs.

Reminder, I didn't check your code logic, check if my default return values make sense, see if I could make the code cleaner, etc. This was just a minimal, mechanical port of your code.

2 Likes

rustlings is also a good set of exercises to learn rust, along with the rust book. Heads up though, this is more geared towards teaching you how the rust language works, not so much general programming exercises like you get from leet code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.