Search code examples
javaalgorithmpalindrome

What is wrong with my java code for Project Euler's program 4? (finding the largest palindrome of 2 3 digit numbers)


This is my code and the answer always seems to 100001 (its not even performing the loop). I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?

public class LargestPalindromes
{

 public static void main(String[] args)
{
    int largest = 100001;

    for(int i = 100; i < 1000; i++)
    {           
        for(int j = 100; j < 1000; j++)
        {
            int mult = i * j;
            if(largest < mult && isPalindrome(mult))
                largest = mult;
        }
    }

    System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}

public static boolean isPalindrome(int mult)
{
    int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
    int largest = 0, count = 0, p =100000;
    int x = mult;

    while(count < 6)
    {
        if(count == 1)
            n1 = x / p;
        else if(count == 2)
            n2 = x / p;
        else if(count == 3)
            n3 = x / p;
        else if(count == 4)
            n4 = x / p;
        else if(count == 5)
            n5 = x / p;
        else if(count == 6)
            n6 = x / p;

        x %= p;

        p /= 10;

        count++;
    }   

    int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));

    return reverse == mult; 
}
}

Solution

  • There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:

    public static boolean isPalindrome(int mult)
    {
    
       int temp=mult;    
       int r,sum=0; 
       while(mult>0){    
         r=mult%10;  //getting remainder  
         sum=(sum*10)+r;    
         mult=mult/10;    
      }    
      if(temp==sum)    
          return true;
      else{
          return false;
      }
    }