File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change 8585 * [ Fibonacci] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/fibonacci.r )
8686 * [ First N Fibonacci] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/first_n_fibonacci.r )
8787 * [ Greatest Common Divisor] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/greatest_common_divisor.r )
88+ * [ Palindrome Check] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/isPalindrome.r )
8889 * [ Josephus Problem] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/josephus_problem.r )
8990 * [ Least Common Multiple] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/least_common_multiple.r )
9091 * [ Modular Exponentiation] ( https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/modular_exponentiation.r )
Original file line number Diff line number Diff line change 1+ # ' Check if a number is a palindrome
2+ # '
3+ # ' @description Checks if an integer is a palindrome (reads the same forwards
4+ # ' and backward) without using strings. Negative numbers are not palindromes.
5+ # ' @param number The integer to check.
6+ # ' @return TRUE if the number is a palindrome, FALSE otherwise.
7+ # ' @examples
8+ # ' isPalindrome(121)
9+ # ' isPalindrome(123)
10+
11+ isPalindrome <- function (number ) {
12+ # Negative numbers are not considered palindromes
13+ if (number < 0L ) {
14+ return (FALSE )
15+ }
16+
17+ original_number <- number
18+ reversed_number <- 0L
19+
20+ # Loop while the number is greater than 0
21+ while (number > 0L ) {
22+ # Get the last digit
23+ remainder <- number %% 10L
24+
25+ # Build the reversed number
26+ reversed_number <- (reversed_number * 10L ) + remainder
27+
28+ # Remove the last digit using integer division
29+ number <- number %/% 10L
30+ }
31+
32+ # Return TRUE if the original and reversed numbers are the same
33+ return (original_number == reversed_number )
34+ }
35+
36+ isPalindrome(121 )
37+ isPalindrome(123 )
38+ isPalindrome(7 )
39+ isPalindrome(- 101 )
You can’t perform that action at this time.
0 commit comments