C# Implementation of Problem 4

View source code here on GitHub!

class p0004
: Euler.IEuler
object Answer ()
 1/*
 2Project Euler Problem 4
 3
 4I couldn't figure out how to do this as efficiently as I would have liked. I am
 5SURE that there is a better way to check if a number is a palindrome, but I
 6could not think of one.
 7
 8Problem:
 9
10A palindromic number reads the same both ways. The largest palindrome made from
11the product of two 2-digit numbers is 9009 = 91 × 99.
12
13Find the largest palindrome made from the product of two 3-digit numbers.
14*/
15using System;
16
17namespace Euler
18{
19    public class p0004 : IEuler
20    {
21        private static string Reverse(string s)
22        {
23            char[] charArray = s.ToCharArray();
24            Array.Reverse(charArray);
25            return new string(charArray);
26        }
27
28        private static bool IsPalindrome(int x)
29        {
30            string rep = x.ToString();
31            return rep == Reverse(rep);
32        }
33
34        public object Answer()
35        {
36            int answer = 0;
37            for (int v = 101; v < 1000; v++)
38                for (int u = 100; u < v; u++)
39                {
40                    int p = u * v;
41                    if (IsPalindrome(p) && p > answer)
42                        answer = p;
43                }
44
45            return answer;
46        }
47    }
48}

Tags: palindrome