Skip to content

Instantly share code, notes, and snippets.

@JFFail
Created June 11, 2015 21:48
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/50cba7b18644a36e4edd to your computer and use it in GitHub Desktop.
Save JFFail/50cba7b18644a36e4edd to your computer and use it in GitHub Desktop.
Ruby Solution To Reddit Daily Programmer #218
#!/usr/env/ruby
#Function to test if the current value is a palindrome!
def is_palindrome(num)
len = num.to_s.length
numArr = num.to_s.split("")
is_pal = true
#Loop through the array, comparing the beginning to the end.
for i in 0...len/2
if numArr[i] != numArr[i * (-1) -1]
is_pal = false
end
end
#Return what we found.
return is_pal
end
#Function to flip the values and add them.
def flip_and_add(num)
flipped = ""
num_string = num.to_s
#Loop through the number, flipping it.
len = num_string.to_s.length
for i in 0...len
flipped = num_string[i] + flipped
end
#Add the numbers.
return num + flipped.to_i
end
#First get the original number to check.
og_num = 196196871
number = og_num
is_pal = false
steps = 0
#Loop through until we hit a palindrome.
while !is_pal
#Check to see if it is one now.
is_pal = is_palindrome(number)
#Either break now or flip and add.
if is_pal
break
else
#Need to flip and add the values.
steps += 1
#Call the function to flip and add.
number = flip_and_add(number)
end
end
#Print the findings.
puts "#{og_num} gets palindromic after #{steps} steps: #{number}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment