Check if a number is Palindrome in C++

C++Server Side ProgrammingProgramming

Here we will see, how to check whether a number is a palindrome or not. The palindrome numbers are the same in both directions. For example, a number 12321 is a palindrome, but 12345 is not a palindrome.

The logic is very straight forward. We have to reverse the number, and if the reversed number is the same as the actual number, then that is a palindrome, otherwise not. Let us see the algorithm to get a better idea.

Algorithm

isPalindrome(n) −

input − The number n

output − true, if the number is a palindrome, otherwise, false

begin
   temp := n
   rev := 0
   while n > 0, do
      rev := rev * 10 + (n mod 10)
      n := n / 10
   done
   if rev = temp, then
      return true
   return false
end

Example

 Live Demo

#include <iostream>
using namespace std;
bool isPalindrome(int number) {
   int temp = number;
   int rev = 0;
   while(number > 0){
      rev = 10 * rev + number % 10; //take the last digit, and attach with the rev number /= 10;
   }
   if(rev == temp)
      return true;
   return false;
}
int main() {
   int n = 12321;
   if(isPalindrome(n)){
      cout << n << " is palindrome number";
   } else {
      cout << n << " is not a palindrome number";
   }
}

Output

12321 is palindrome number
raja
Published on 22-Oct-2019 06:16:51
Advertisements