Palindrome program in C++

Written by

Juhi Kamdar

Palindrome number program in C++

If a number remains the same when reversed, it is known as a palindrome number.

There are two ways through which we can do this.

  • Using string reverse method
  • Use of modulo operator

Using string reverse method

Algorithm:

  1. Convert number to a string
  2. Copy that string to another string
  3. Reverse the string
  4. Compare the reversed string and the original string

Code:

#include<iostream>

#include<cstring> //string library

#include <algorithm> //library containing begin() and end()

using namespace std;

int main()

{

int number,remainder;

cin>>number;

string s1=to_string(number);//storing string value of number in s1

string s2=s1;//copy contents of s1

reverse(s2.begin(), s2.end()); //reversing the complete string s2

if(s1==s2)

cout<<"palindrome";

else

cout<<"not a palindrome";

return 0;

}

Advantage:

  • Easy to understand and execute

Disadvantage:

  • Wastage of more memory due to conversion in string

Using modulo operator

Algorithm:

  1. Save the number in another variable for future use.
  2. Now, reverse the number using while loop.
  3. Compare the reversed number and the original number.

Code:

#include<iostream>

using namespace std;

int main()

{

int num,rem;

cin>>num;

int duplicatenum=num;

int newnum=0;

while(num!=0) // till all digits of num are dealt with

{

rem=num%10; //remainder,last digit extracted

newnum=newnum*10+rem; // connect rem to newnum

num=num/10; //trimming last digit from num

}

if(newnum==duplicatenum)

cout<<"palindrome";

else

cout<<"not a palindrome";

return 0;

}

Advantage:

  • Faster execution
  • Uses less space
Palindrome program in C++