Problem #36 Difficulty: 5%

Double-base Palindromes

Solution Language: Java

The problem

Sum all numbers below one million that are palindromes in both base 10 and base 2 (without leading zeros).

My solution

Plain brute force. For every i below a million I build the decimal string with Integer.toString and the binary string with Integer.toBinaryString, and check each by comparing characters from both ends toward the middle. Neither method emits leading zeros, so the problem’s leading-zero rule is handled for free. A million iterations with two short strings each runs quickly.

Notes

Only odd numbers can be binary palindromes: the leading bit is always 1, so the last bit must be too.