1

I'm working my way through Project Euler, and on problem 4 my palindrome code isn't working. Specifically, it returns 998001 (999*999) as if it were a palindrome.

The code to check the palindrome works, but it keeps looping and replacing the max value despite it not being a palindrome. What am I missing?

Thanks for your help

public int palindromeNumber()
{
    int max=0;
    for(int x = 100; x<1000; x++)
    {
        for(int y = 100; y<1000; y++)
        {
            int z = x*y;
            StringBuilder num = new StringBuilder(Integer.toString(z));
            StringBuilder rev = num.reverse();
            if(num==rev)
            {
                max=z;
            }
        }
    }
    return max;
}
cuttlefish
  • 11
  • 1

3 Answers3

5

If you take a look on the StringBuilder.reverse() method it returns the reference to the same object (num in your case)

@Override
public StringBuilder reverse() {
    super.reverse();
    return this;
}

So you rev == num is always true and you get the 999*999 because it is the end of a loop

Anatoly D.
  • 317
  • 2
  • 10
4

Your code is correct, however, as the comments have pointed out, you are comparing addresses instead of strings.

A String is an object, not a primitive type, so '==' will not work when you compare original and reversed.

Instead, you need to use the .equals(String) method.

Here's a one-liner proof of concept:

max = (num.equals(new StringBuilder(Integer.toString(z)).reverse())) ? z : max;

Note:

For performance reasons, you might wanna try to implement this numerically, conversions and parsing take time.

Quick proof of concept:

 num = origNum
 while (num > 0)
 {
      digit = num % 10;
      rev = rev * 10 + digit;
      num = num / 10;
 }

 if (origNum == rev) //max..
Luke Kot-Zaniewski
  • 1,161
  • 11
  • 12
Athamas
  • 609
  • 5
  • 16
0
Please make some changes as - 

public static int palindromeNumber()
{
    int max=0;
    for(int x = 100; x<1000; x++)
    {
        for(int y = 100; y<1000; y++)
        {
            int z = x*y;
            StringBuilder num = new StringBuilder(Integer.toString(z));
            StringBuilder numberCopy = new StringBuilder(num);
            StringBuilder rev = num.reverse();

            if(numberCopy.toString().equals(rev.toString()))
            {
                max=z;
            }
        }
    }
    return max;
}

The problem in your code is that , when you use rev = num.reverse(); Then each time in loop It modify the same object- num with reversed number and then assign it to rev. Now both reference- num & rev pointing to the same modified object.(num and rev value is 999 in last iteration)

Then you are using == which check reference are pointing to the same object or not, and here num and rev points to same object so condition is true every time.

Solution -

  1. copy object to another object before modifying which can be used later for comparison.

  2. use equals to compare values instead ==.

Ravi
  • 21
  • 4