|
| 1 | +# Palindrome Number Checking in Ruby |
| 2 | + |
| 3 | +# Checks if a given integer is a palindrome without converting it to a string. |
| 4 | +# A palindrome is a number that reads the same backward as forward. |
| 5 | +# Negative numbers are not considered palindromes by this definition. |
| 6 | +# |
| 7 | +# @param number [Integer] The integer to check. |
| 8 | +# @return [Boolean] true if the number is a palindrome, false otherwise. |
| 9 | +# |
| 10 | +# Examples: |
| 11 | +# is_palindrome(121) #=> true |
| 12 | +# is_palindrome(123) #=> false |
| 13 | +# is_palindrome(7) #=> true |
| 14 | +# is_palindrome(0) #=> true |
| 15 | +# is_palindrome(-121) #=> false |
| 16 | +def is_palindrome(number) |
| 17 | + # Negative numbers are not considered palindromes |
| 18 | + return false if number < 0 |
| 19 | + |
| 20 | + # Single digits are always palindromes |
| 21 | + # return true if number < 10 # This line is optional but efficient |
| 22 | + |
| 23 | + original_number = number |
| 24 | + reversed_number = 0 |
| 25 | + |
| 26 | + # Loop while the number is greater than 0 |
| 27 | + while number > 0 |
| 28 | + # Get the last digit |
| 29 | + remainder = number % 10 |
| 30 | + |
| 31 | + # Build the reversed number |
| 32 | + reversed_number = (reversed_number * 10) + remainder |
| 33 | + |
| 34 | + # Remove the last digit using integer division |
| 35 | + number /= 10 |
| 36 | + end |
| 37 | + |
| 38 | + # Return true if the original and reversed numbers are the same |
| 39 | + original_number == reversed_number |
| 40 | +end |
| 41 | + |
| 42 | +# --- Examples --- |
| 43 | +puts "Is 121 a palindrome? #{is_palindrome(121)}" # Output: true |
| 44 | +puts "Is 123 a palindrome? #{is_palindrome(123)}" # Output: false |
| 45 | +puts "Is 7 a palindrome? #{is_palindrome(7)}" # Output: true |
| 46 | +puts "Is 0 a palindrome? #{is_palindrome(0)}" # Output: true |
| 47 | +puts "Is -101 a palindrome? #{is_palindrome(-101)}" # Output: false |
| 48 | +puts "Is 1221 a palindrome? #{is_palindrome(1221)}" # Output: true |
0 commit comments