As we know, it is easy to get digits from right to left via the / and % operators. For example, digits in the
number 123 from right to left are 3, 2, and 1. A reversed number 321 is constructed with these three digits.
Let’s check whether the reversed number is identical to the original one. If it is, the original number is a
palindrome.
The implementation is shown in Listing 2-7.
Listing 2-7. C Code to Verfiy Palindrome Numbers (Version 2)
The implementation is shown in Listing 2-7.
Listing 2-7. C Code to Verfiy Palindrome Numbers (Version 2)
/* It returns 1 when number is palindrome, otherwise returns 0. */
int IsPalindrome_solution2(unsigned int number) {
int reversed = 0;
int copy = number;
while(number != 0) {
reversed = reversed * 10 + number % 10;
number /= 10;
}
return (reversed == copy) ? 1 : 0;
}
Source Code:
001_PalindromeNumber.c
Test Cases:
-
Palindrome numbers with odd length
-
Palindrome numbers with even length
-
Non-palindrome numbers
No comments:
Post a Comment