Palindrome Number in R

Palindrome Number LeetCode Problem

When given an integer, print if it’s a palindrome number (true) or false.

Example 1:

Using base r’s rev function this is pretty simple as it handles reversing the input.

Palindrome_Check <- function(Input){

  paste(rev(unlist(strsplit(as.character(Input), ""))), collapse = "") == Input
}
> Palindrome_Check(121)
[1] TRUE
> Palindrome_Check(1215)
[1] FALSE

Example 2:

If we didn’t want to use rev, we can add a loop to reverse the input

Palindrome_Check_2 <- function(Input){
 
x <- unlist(strsplit(Input, ""))
z = ""
 
for (i in length(x):1){
 
z = paste0(z, x[i])  
 
}

z == Input
}
> Palindrome_Check_2("121")
[1] TRUE
> Palindrome_Check_2("1215")
[1] FALSE

Leave a Reply

Your email address will not be published. Required fields are marked *