Find the largest palindrome made from the product of two 3-digit numbers - Javascript

前端 未结 21 1443
感情败类
感情败类 2020-12-28 17:16

Can anyone tell me what\'s wrong with the code. Find the largest palindrome made from the product of two 3-digit numbers.

function largestPalind         


        
21条回答
  •  春和景丽
    2020-12-28 17:50

    instead of creating an Array or ArrayList to store all palindromes, I just created another variable max and stored highest valued palindrome in it.

    My code is in Java, but you can understand the logic from it. Here is my code to better explain what I said (read comments):

    package euler;
    import java.util.ArrayList; import java.util.Collections;
    
    public class Problem4 {
        public static void main (String[] args)
        {
            int product=0;
                int max=0;
            for(int i=999;i>100;i--)
            {
                for (int j=i;j>100;j--)
                {
                    product=i*j;
    
                    if(isPalindrome(product))
                    {
                        //Just store maximum value of product.
                        //Following if loop is required in your code,in place of return i*j;
                                        if(product>max)
                            { max=product; }
                    }
                }
            }
            System.out.println(max);    
        }
        //might be inefficient to create StringBuilder and again String to compare.
        public static boolean isPalindrome(int product)
        {
            boolean isPalindrome=false;
            StringBuilder temp = new StringBuilder(Integer.toString(product)).reverse();
            if(temp.toString().equals(Integer.toString(product)))
            {
                isPalindrome=true;
            }
            return isPalindrome;
        }
    }
    

    What you are doing is returning and breaking out of the loop as soon as you get the first palindrome. Which in your case is not the maximum value palindrome.

    Instead use an if condition and keep a track of maximum values and let the loop continue till end.

    I have added the if condition that lets the loop running and registers the value.

    Got the correct answer from this code.

    PS. Thanks Xan for your input. I guess I could've explained it better first time.

提交回复
热议问题