Friday, January 2, 2009

Project Euler and PowerShell - Problem 36

This one looked fun!

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

Here is my (non-optimized) solution.
# Sum all numbers less then 1,000,000 that are
#
palindromic in base 10 and base 2
function Reverse-Parameter {
param ([string]$number)
for ($i = $number.length - 1; $i -ge 0; $i--)
{
$b = $b + ($number.substring($i,1))
}
[
decimal]$b
}

$max = 1000000;$sum = 0
for ($i=0;$i -lt $max;$i++)
{
$k = Reverse-Parameter $i
if($i -eq $k)
{
$bi = [Convert]::ToString($i,2)
$rbi = Reverse-Parameter $bi
if($bi -eq $rbi)
{
$sum = $sum + $i
"{0}`t{1}`t`t{2}" -f $i,$bi,$sum
}
}
}

No comments: