Created
June 8, 2015 19:58
-
-
Save JFFail/81e602536ccb62b86768 to your computer and use it in GitHub Desktop.
Solution to Reddit Daily Programmer #218
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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