Skip to content

Instantly share code, notes, and snippets.

@JFFail
Created June 8, 2015 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JFFail/81e602536ccb62b86768 to your computer and use it in GitHub Desktop.
Save JFFail/81e602536ccb62b86768 to your computer and use it in GitHub Desktop.
Solution to Reddit Daily Programmer #218
#http://www.reddit.com/r/dailyprogrammer/comments/38yy9s/20150608_challenge_218_easy_making_numbers/
#Function to see if the number is already a palindrome or not.
function IsPalindrome
{
param($num)
#Find the length.
$len = ([string]$num).Length
#Check it.
$counter = 0
$currentlyPal = $true
while($counter -lt ($len / 2) -and $currentlyPal)
{
#See if in the next iteration it's currently a palindrome.
if(-not(([string]$num)[$counter] -eq ([string]$num)[$counter * (-1) - 1]))
{
$currentlyPal = $false
}
#Increment the counter.
$counter++
}
return $currentlyPal
}
#Function to reverse the number and flip it.
function FlipAndAdd
{
param($originalNum)
#Flip it.
$newNum = ""
for($i = 0; $i -lt ([string]$originalNum).Length; $i++)
{
$newNum = ([string]$originalNum)[$i] + $newNum
}
#Add the numbers and return.
return $originalNum + [int64]$newNum
}
#First is the number to check.
$initNum = 286
$number = $initNum
#Keep track of the number of steps.
$steps = 0
#First check if it's a palindrome.
do {
$checkNumber = IsPalindrome -num $number
#Reverse and add if it isn't a palindrome yet.
if(-not($checkNumber))
{
$number = FlipAndAdd -originalNum $number
#Increment the number of steps.
$steps++
}
else
{
$checkNumber = $true
}
} while(-not($checkNumber))
Write-Host "$initNum gets palindromic after $steps steps: $number"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment