Created
September 30, 2019 21:45
-
-
Save dudo/0cea15cc2ae56202f688fde93b5ba24b to your computer and use it in GitHub Desktop.
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
# Return a boolean indicating whether the number is a palindrome. Raises a | |
# TypeError if the argument is not an integer | |
# | |
# Caveat: Try to accomplish this without converting the number to a string. | |
# The goal is to understand your approach to a problem with constraints | |
# rather than seeing how quickly you can jump to an easy solution. | |
# | |
# Example | |
# palindrome?(1001) => true | |
# palindrome?(1234) => false | |
# palindrome?(1) => true, `1` backwards is `1` | |
# palindrome?(10) => false, read backward, the number is effectively `1` | |
# palindrome?(-121) => false, the `-` sign is included | |
module Positional | |
refine Integer do | |
def position_rtl(index) | |
self / (10**index) % 10 | |
end | |
end | |
end | |
class Exercise | |
using Positional | |
attr_reader :number | |
def initialize(number) | |
@number = number | |
raise TypeError unless number.kind_of?(Integer) | |
end | |
def palindrome? | |
return false if number < 0 | |
size = Math.log(number, 10).floor + 1 | |
size.times do |i| | |
return false unless number.position_rtl(size - 1 - i) == number.position_rtl(i) | |
end | |
true | |
end | |
end | |
Exercise.new(1001).palindrome? | |
Exercise.new(1234).palindrome? | |
Exercise.new(1).palindrome? | |
Exercise.new(10).palindrome? | |
Exercise.new(-121).palindrome? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment