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.)

No problems here. Flew through this one fast. The trick is to compare strings, not numbers. But use the Integer class to do the base conversion to string for you.

public class Euler36
{
    public static void main(String[] args)
    {
        System.out.format(“Problem 36:\n”);
        Euler36 e = new Euler36();
        System.out.format(“Answer = %s\n”, e.Problem());
    }
    public String Problem ()
    {
        int sum = 0;
        for (int i10 = 1; i10 <= 1000000; i10++)
        {
            String r10 = “”;
            String r2 = “”;
            String s10 = Integer.toString(i10);
            String s2 = Integer.toBinaryString(i10);
            for (int i = s10.length()-1; i >=0; i–)
                r10 += s10.charAt(i);
            for (int i = s2.length()-1; i >=0; i–)
                r2 += s2.charAt(i);
            if (s10.equals(r10) && s2.equals(r2))
            {
                sum += i10;
                System.out.format(“%s:%s %s:%s\n”, s10, r10, s2, r2);
            }
        }
        return String.valueOf(sum);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s