diff --git a/lib/integer_palindrome_check.rb b/lib/integer_palindrome_check.rb index dd4deea..63b6596 100644 --- a/lib/integer_palindrome_check.rb +++ b/lib/integer_palindrome_check.rb @@ -1,4 +1,32 @@ # Returns true if the input positive integer number forms a palindrome. Returns false otherwise. +require 'pry' def is_palindrome(number) - raise NotImplementedError + return false if number == nil || number < 0 + return true if number == 0 + + reversed_num = 0 # n + duplicate = number # n + + while duplicate > 0 + reversed_num *= 10 + last_num = duplicate % 10 # only contains 1 digit at a time + reversed_num += last_num + duplicate -= last_num + duplicate /= 10 + end + + if number == reversed_num + return true + else + return false + end end + +#Time complexity: O(n) where n is the length/size of the input. +#Depending on how many digits the number is the while loop will +# continue to execute O(n - 1), but we drop the 1 because it is insignificant. + +#Space complexity: O(n) where n is the length/size of the input. +# In this solution I defined 3 variables, 2 of which take +#up the same space as the input's length. The last_num variable only +#holds one digit at a time diff --git a/specs/integer_palindrome_check_spec.rb b/specs/integer_palindrome_check_spec.rb index f7fb968..5dfcaf4 100644 --- a/specs/integer_palindrome_check_spec.rb +++ b/specs/integer_palindrome_check_spec.rb @@ -23,7 +23,7 @@ it "nil object is not an integer" do is_palindrome(nil).must_equal false end - + it "single digit palindrome" do is_palindrome(9).must_equal true end