In this program, You will learn how to check a number is a palindrome or not in R.
Example: How to check a number is a palindrome or not in R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{ n = as.integer(readline(prompt = "Enter a number :")) rev = 0 num = n while (n > 0) { r = n %% 10 rev = rev * 10 + r n = n %/% 10 } if (rev == num) { print(paste("Number is palindrome :", rev)) } else{ print(paste("Number is not palindrome :", rev)) } } |
Output:
1 2 3 4 |
Enter a number :434 [1] "Number is palindrome : 434" |
A palindrome is a word, number, or other sequence of characters that reads the same backward as forward.
The function does this by first reading in a number from the user and then storing it in a variable called n
. It then initializes a variable rev
to 0 and a variable num
to n
.
Next, the function enters a while
loop which will iterate as long as n
is greater than 0. Inside the loop, it computes the remainder of n
divided by 10 and stores it in a variable r
. It then updates rev
by multiplying it by 10 and adding r
. Finally, it updates n
by dividing it by 10 and taking the integer part.
After the loop ends, the function checks if rev
is equal to num
. If it is, it prints a message saying that the number is a palindrome. If it is not, it prints a message saying that the number is not a palindrome.