Tag Archives: palindrome

Euler Problem 55

Not too tricky. Use the BigInteger class.

    import java.math.*;

    public class Euler55
    {
        public static void main(String[] args)
        {
            Euler55 e = new Euler55();
            System.out.format(“Problem: %s\n”, e.getClass().getName());
            System.out.format(“Answer = %s\n”, e.Problem());
        }
        public String Problem ()
        {
            int count = 0;
            for (int n = 1; n < 10000; n++)
            {
                BigInteger N = new BigInteger (String.valueOf(n));
                boolean flag = true;
                for (int i = 1; i <= 50; i++)
                {
                    N = N.add(new BigInteger (Rev(N.toString())));
                    System.out.format(“Number:%d Iteration:%d Sum:%s\n”,n, i, N.toString());
                    if (N.toString().equals(Rev(N.toString())))
                    {
                        System.out.format(“Palindrome in %d. Count = %d\n”,i,count);
                        flag = false;
                        break;
                    }
                }
                if (flag)
                    count++;
            }
            return String.valueOf(count);
        }
        public String Rev (String n)
        {
            return new StringBuffer(n).reverse().toString();
        }
    }