Project Euler

A Taste of Number Theory

Problem 36: Double-base Palindromes

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. (Please note that the palindromic number, in either base, may not include leading zeros.)

The Catch

How to convert a decimal number to binary.
How to check if a number is palindromic.

The Light

To convert a decimal number to binary, divide the number by 2 and list out the remainders for every division until the quotient is reduced to 0. Reverse the remainder list to find the binary result.

For example, convert 12 to binary:

Quotient

Remainer

12/2

0

6/2

0

3/2

1

1/2

1

12 in binary is 1100. You can either implement this approach or use Java's Integer class' built-in function that converts decimal number to binary.

Use the discussion in Problem 4 on how to check if a number is palindromic.



The Code

public class Problem36
{
  public static void main(String[] args)
  {
    int sum = 0;

    for(int i = 1; i < 1000000; i++)
    {
      String s = Integer.toString(i);
      if(isPalin(s) && isPalin(Integer.toBinaryString(i)))
        sum += i;
    }
    System.out.println(sum);
  }

  public static boolean isPalin(String s)
  {
    for(int i = 0; i < s.length()/2; i++)
    {
      if(s.charAt(i) != s.charAt(s.length() - 1 - i))
        return false;
    }
    return true;
  }
}