Sunday 12 April 2009

PROJECT EULER #36

Link to Project Euler problem 36

The decimal number, 585 = 1001001001_(2) (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)

using System;
using System.Text;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 36
DateTime start = DateTime.Now;
int sum = 0;
for (int i = 1; i < 1000000; i++)
{
if(IsPalindrome(i.ToString()))
{
sum += IsPalindrome(ToBinary(i))
? i
: 0;
}
}
Console.WriteLine(sum);
TimeSpan time = DateTime.Now-start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static string ToBinary(int n)
{
var number = new StringBuilder();
int rem;
while(n!=0)
{
n=Math.DivRem(n, 2, out rem);
switch (rem)
{
case 0:
number.Append(0);
break;
case 1:
number.Append(1);
break;
default:
break;
}
}
var c = number.ToString().ToCharArray();
Array.Reverse(c);
string s = new string(c);
while (s.StartsWith("0"))
{
s.Remove(0, 1);
}
return s;
}
public static bool IsPalindrome (string s)
{
char[] q = s.ToCharArray();
Array.Reverse(q);
string r = new string(q);
if (s.Equals(r))
return true;
return false;
}
}
}

No comments: