Find the largest palindrome made from the product of two 3-digit numbers. (Java)

后端 未结 4 2033
难免孤独
难免孤独 2021-01-16 20:21

I am having a bit of trouble solving Project Euler question 4. I am inexperienced in programming and didn\'t really understand other answers. I managed to write a code that

4条回答
  •  粉色の甜心
    2021-01-16 20:44

    Here is my take on the same question...

    It is way more easier to create a list, that we know will be filled from smallest to the largest, because counter numbers only rize...

            List palindrome = new ArrayList<>(); // create integer list
    
        for ( int i = 900; i<999; i++){
            for ( int j = 900; j < 950; j++){
                // both counter numbers are bigger than 900
                // because there will those two int's be, logically
                String newMul = String.valueOf(i * j);  // make it string for palindrome comparation
                String strRev = new StringBuilder(newMul).reverse().toString(); // rotate previous string
                                                                                // for palindrome comparation 
                if(newMul.equals(strRev)){  //if its equal
                palindrome.add(i * j);      //will put multiplication result of i and j into list
                }
            }
        }
        System.out.println(palindrome.get(palindrome.size()-1)); // last number in list is the 
    }                                                            // biggest so lets print it out
    

    Basicly, you just need little casting to se if it is a palindrome, but if it is, just multiply i and j to put them into list... It will loop for a long time, but that way you checked all the numbers bigger than 900 for the biggest palindrome...

    Hope I helped...

提交回复
热议问题