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

前端 未结 21 1437
感情败类
感情败类 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:37

    Most of the answers here are correct. If you want to save going through 900*900 loops, you can just loop through all palindromes between 10000 and 998001 and find if they are divisible by 3 digit number.

     static void largestpalindromeproduct(){
       int a=999,b=999,c=a*b,loopcounter=0;
       while(c>10000){
           loopcounter++;
           c--;
           if(isPalindrome(c))
               if(isDivisible(c))
               break;
       }
    
       System.out.println(" largest : " + c+ "\nloops:"+ loopcounter);       
    }
    static boolean isDivisible(int n){
        int a=999;
        while(a>=100){
            if(n%a==0){
                if(secondDividerIs3Digit(n,a))
                return true;
            }
            a--;
        }
        return false;
    }
    static boolean secondDividerIs3Digit(int n, int a){
        Integer b=n/a;
        if(b.toString().length()==3)
            return true;
        return false;
    }
    
    static boolean isPalindrome(int n){
        Integer i=new Integer(n);
        String p=i.toString();
        StringBuffer s=new StringBuffer(i.toString());
        s.reverse();
        if(p.equals(s.toString()))
            return true;
        return false;
    }
    

提交回复
热议问题