C#: Euler 36

https://projecteuler.net/problem=36

The decimal number, 585 = 10010010012 (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.

//Euler 36
static void Main(string[] args)
{
    int num = 0;
    int sum = 0;
    while (num < 1000000)
    {
        num += 1;
        string sBits = Convert.ToString(num, 2);
        string sNum = num.ToString();
        if (isSym(sNum) && isSym(sBits))
        {
            sum += num;
        }
    }
    Console.WriteLine("Answer : "+sum);
}
 
public static string Reverse(string s)
{
    char[] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}
 
public static bool isSym(string n)
{
    double half = n.Length / 2;
    string a  = n.ToString();
    string b  = n.ToString();
    b = Reverse(b);
    string new_a = "";
    string new_b = "";
    for (int i = 0; i < half; i++)
    {
        new_a += a[i];
        new_b += b[i];
    }
    if (new_a == new_b)
        return true;
    return false;
}

Leave a Reply

Your email address will not be published.