Palindrome Number.
A palindrome number is a number that reads the same backward as forward. In other words, the digits of a palindrome number remain unchanged when read from left to right and from right to left.
Example: 121, 454, and 12321 are palindrome numbers.
Algorithm to Check Palindrome Number.
Step 1: Input the number from the user.
Step 2: Create a copy of the original number to compare later.
Step 3: Initialize variables to store the reverse of the number and the remainder.
Step 4: Use a loop to reverse the digits of the number:
- a) Extract the last digit of the number using the modulus (%) operator.
- b) Add the last digit to the reversed number after moving the previous digits one place left using multiplication (*= 10).
- c) Remove the last digit from the original number using integer division ( /= 10).
- d) Repeat the above steps until the original number becomes 0.
Step 5: Compare the reversed number with the copy of the original number.
Step 6: If the reversed number is equal to the original number, it is a palindrome. Otherwise, it is not.
Program to Check Palindrome Number.
// c code implementation to check palindrome number #include <stdio.h> int main() { int num, originalNum, reversedNum = 0, remainder; printf("Enter an integer: "); scanf("%d", &num); originalNum = num; // Reverse the number while (num != 0) { remainder = num % 10; reversedNum = reversedNum * 10 + remainder; num /= 10; } // Compare with the original number if (reversedNum == originalNum) { printf("%d is a palindrome number.\n", originalNum); } else { printf("%d is not a palindrome number.\n", originalNum); } return 0; }
Enter an integer: 12321
12321 is a palindrome number.
Time Complexity: O(n) where n is the number of digits present in the given number.
Space Complexity: O(1) no extra space is required to solve this problem.
Similar articles:
No comments:
Post a Comment