diff --git a/DIRECTORY.md b/DIRECTORY.md index 376ebebd..a7a1e1b5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -85,6 +85,7 @@ * [Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/fibonacci.r) * [First N Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/first_n_fibonacci.r) * [Greatest Common Divisor](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/greatest_common_divisor.r) + * [Palindrome Check](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/isPalindrome.r) * [Josephus Problem](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/josephus_problem.r) * [Least Common Multiple](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/least_common_multiple.r) * [Modular Exponentiation](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/modular_exponentiation.r) diff --git a/mathematics/isPalindrome.r b/mathematics/isPalindrome.r new file mode 100644 index 00000000..22de7050 --- /dev/null +++ b/mathematics/isPalindrome.r @@ -0,0 +1,39 @@ +#' Check if a number is a palindrome +#' +#' @description Checks if an integer is a palindrome (reads the same forwards +#' and backward) without using strings. Negative numbers are not palindromes. +#' @param number The integer to check. +#' @return TRUE if the number is a palindrome, FALSE otherwise. +#' @examples +#' isPalindrome(121) +#' isPalindrome(123) + +isPalindrome <- function(number) { + # Negative numbers are not considered palindromes + if (number < 0L) { + return(FALSE) + } + + original_number <- number + reversed_number <- 0L + + # Loop while the number is greater than 0 + while (number > 0L) { + # Get the last digit + remainder <- number %% 10L + + # Build the reversed number + reversed_number <- (reversed_number * 10L) + remainder + + # Remove the last digit using integer division + number <- number %/% 10L + } + + # Return TRUE if the original and reversed numbers are the same + return(original_number == reversed_number) +} + +isPalindrome(121) +isPalindrome(123) +isPalindrome(7) +isPalindrome(-101)