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

后端 未结 4 2072
难免孤独
难免孤独 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 21:07

    Here is a method which loops over all numbers from 1-999 and multiplies them with all possible numbers from 1-999. You will need to define a method isPalindrome(int) that will check if a given int is a palindrome.

    //save the largest number
    int largest = 0;
    
    //loop over every possible product of numbers from 100-999
    for (int i = 999; i >= 100; i--) {
     for (int j = i; j >= 100; j--) {
      int curr = i * j;
    
      //if the current number is a palindrome and is greater than the last found largest
      if (isPalindrome(curr) && curr > largest) {
    
       //save it as the new largest found number
       largest = curr;
      }
     }
    }
    

    The isPalindrome method might look like this:

    private static boolean isPalindrome(Integer possible) {
        String toStr = possible.toString();
        int len = toStr.length();
        if (len % 2 == 1) {
            len = len - 1;
        }
    
        for (int i = 0; i < len / 2; i++) {
            if (toStr.charAt(i) != toStr.charAt(toStr.length() - (1 + i))) {
                return false;
            }
        }
    
        return true;
    }
    

提交回复
热议问题