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

前端 未结 17 1010
天涯浪人
天涯浪人 2021-02-02 04:27
package testing.project;

public class PalindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i+         


        
17条回答
  •  抹茶落季
    2021-02-02 05:13

    Since we are not cycling down both iterators (num1 and num2) at the same time, the first palindrome number we find will be the largest. We don’t need to test to see if the palindrome we found is the largest. This significantly reduces the time it takes to calculate.

    package testing.project;
    public class PalindromeThreeDigits {
        public static void main(String[] args) {
    
        int limit = 99;
        int max = 999;
        int num1 = max, num2, prod;
    
        while(num1 > limit)
        {
            num2 = num1;
            while(num2 > limit)
            {
                total = num1 * num2;
                StringBuilder sb1 = new StringBuilder(""+prod);
                String sb2 = ""+prod;
                sb1.reverse();
                if( sb2.equals(sb1.toString()) ) {    //optimized here
                    //print and exit
                }
                num2--;
            }
            num1--;
        }
    
     }//end of main
     }//end of class PalindromeThreeDigits
    

提交回复
热议问题