Project Euler: Problem 36 – Double-base palindromes

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

Idea:

While researching how to convert a decimal to binary, I saw that the BigInteger class has a toString(int radix) method that can convert the output of a BigInteger into different bases (in this case, base 2). I then fed the decimal number and binary number into a palindrome method I wrote for Problem 4. If both were palindromes, I added the decimal number to a running total.

int answer = 0;

for(int i = 0; i < 1000000; i++) {
   if(isPalindrome(i) && isPalindrome(BigInteger.valueOf(i).toString(2))) {
      answer += i;
   }
}

System.out.println("Answer: "+answer);

Note: “isPalindrome” is a helper method I wrote that checks if the given input (Number/String) is a palindrome.

Project Euler: Problem 4 – Largest palindrome product

Problem 4:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
 
Find the largest palindrome made from the product of two 3-digit numbers.

Idea:

The only idea I had on how to solve this was with a brute-force method of using 2 nested loops, multiplying the loop counters together, and checking to see if the product was a palindrome.
 
It wasn’t until after I solved this that I saw others used mathematical reasoning / deduction to reduce the overall number of iterations.

int answer = -1;
int fact1 = -1;
int fact2 = -1;

for(int i = 999; i >= 100; i--) {
   for(int j = 999; j >= 100; j--) {
      int product = (i*j);

      if(isPalindrome(product) && (product > answer)) {
         answer = product;
         fact1 = i;
         fact2 = j;
         break;
      }
   }
}

System.out.println("\nAnswer: "+answer+" ("+fact1+","+fact2+")");

Note: “isPalindrome()” is a utility method I wrote that accepts a number (int, long, BigInteger, etc…) and returns true if the number is a palindrome, false otherwise.