Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 39 additions & 0 deletions mathematics/isPalindrome.r
Original file line number Diff line number Diff line change
@@ -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)