Largest palindrome product - euler project

后端 未结 15 2097
广开言路
广开言路 2020-12-10 22:05

I was trying to solve project Euler problem 4 which is:

A palindromic number reads the same both ways. The largest palindrome made from the product of tw

15条回答
  •  心在旅途
    2020-12-10 22:45

    Here is a solution that doesn't iterate through all the 6-digit numbers:

    public static boolean isPalindrome(int nr) {
        int rev = 0;                    // the reversed number
        int x = nr;                     // store the default value (it will be changed)
        while (x > 0) {
            rev = 10 * rev + x % 10;
            x /= 10;
        }
        return nr == rev;               // returns true if the number is palindrome
    }
    
    public static void main(String[] args) {
    
        int max = -1;
    
        for ( int i = 999 ; i >= 100 ; i--) {
            for (int j = 999 ; j >= 100 ; j-- ) {
                int p = i * j;
                if ( max < p && isPalindrome(p) ) {
                    max = p;
                }
            }
        }
        System.out.println(max > -1? max : "No palindrome found");
    }
    

    Edit:

    An improved solution for the main method ( according to Peter Schuetze ) could be:

    public static void main(String[] args) {
    
        int max = -1;
    
        for ( int i = 999 ; i >= 100 ; i--) {
            if ( max >= i*999 ) { 
                break;
            }
            for (int j = 999 ; j >= i ; j-- ) {             
                int p = i * j;
                if ( max < p && isPalindrome(p) ) {
                    max = p;
                }
            }
        }       
        System.out.println(max > -1? max : "No palindrome found");
    }
    

    For this particular example, the time is about 2 times better, but if you have bigger numbers, the improvement will be more significant.

    Output:

    906609
    

提交回复
热议问题