Euler problem number #4

前端 未结 14 1876
萌比男神i
萌比男神i 2021-01-03 11:00

Using Python, I am trying to solve problem #4 of the Project Euler problems. Can someone please tell me what I am doing incorrectly? The problem is to Find the larg

14条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 11:24

    This is what I did in Java:

    public class Euler0004
    {
        //assumes positive int
        static boolean palindrome(int p)
        {
            //if there's only one char, then it's
            //  automagically a palindrome
            if(p < 10)
                return true;
    
            char[] c = String.valueOf(p).toCharArray();
    
            //loop over the char array to check that
            //  the chars are an in a palindromic manner
            for(int i = 0; i < c.length / 2; i++)
                if(c[i] != c[c.length-1 - i])
                    return false;
    
            return true;
        }
    
    
        public static void main(String args[]) throws Exception
        {
            int num;
            int max = 0;
    
            //testing all multiples of two 3 digit numbers.
            // we want the biggest palindrome, so we
            // iterate backwards
            for(int i = 999; i > 99; i--)
            {
                // start at j == i, so that we
                //  don't calc 999 * 998 as well as
                //  998 * 999...
                for(int j = i; j > 99; j--)
                {
                    num = i*j;
    
                    //if the number we calculate is smaller
                    //  than the current max, then it can't
                    //  be a solution, so we start again
                    if(num < max)
                        break;
    
                    //if the number is a palindrome, and it's
                    //  bigger than our previous max, it
                    //  could be the answer
                    if(palindrome(num) && num > max)
                        max = num;
                }
            }
    
            //once we've gone over all of the numbers
            //  the number remaining is our answer
            System.out.println(max);
    
        }
    }
    

提交回复
热议问题