Write a C++ program that enters a integer number and use a stack to determine if the number is a Palindrome.

A palindrome number is a number that is same after reverse. For example 121, 34543, 343, 131, 48984 are the palindrome numbers.

Write a C++ program that enters a integer number and use a stack to determine if the number is a Palindrome.

I need help with this program. I tried but my professor is saying to USE STACK to determine. So im stuck here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <stack>
#include <string>

int main()
{
    std::stack<char> stack;
    std::string word;
    std::cout << "Enter a number: ";
    std::cin >> word;
    
    const int length = word.length();
    for( int i = 0; i < length/2; ++i )
    {
        stack.push( word[i] );
        stack.push( word[length-1-i] );
    }
    while( ! stack.empty() )
    {
        char tmp1 = stack.top();
        stack.pop();
        char tmp2 = stack.top();
        stack.pop();
        if( tmp1 != tmp2 )
        {
            std::cout << word << " is not a palindrome.\n";
            return 0;
        }
    }
    std::cout << word << " is a palindrome.\n";
}


Whereby using a stack is pretty useless in the code above. A shorter solution would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

int main()
{
    std::string word;
    std::cout << "Enter a number: ";
    std::cin >> word;
    
    const int length = word.length();
    for( int i = 0; i < length/2; ++i )
    {
        if( word[i] != word[length-1-i] )
        {
            std::cout << word << " is not a palindrome.\n";
            return 0;
        }
    }
    std::cout << word << " is a palindrome.\n";
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

bool isPalindrome( const string &word )
{
   string S = word;        // pseudo-stack
   for ( char c : word )
   {
      if ( c != S.back() ) return false;
      S.pop_back();
   }
   return true;
}

int main()
{
   string word; 
   cout << "Enter a number: ";   cin >> word;
   cout << word << ( isPalindrome( word ) ? " is " : " is not " ) << "a palindrome.\n";
}
I need help with this program.


What help? The code in the first post compiles, runs and produces the expected answer. I'd comment that int should be size_t as this the type returned by .length()

If you are required to use a stack, then you are required. It's not how would do it for real if required - but a lot of given exercises require things done differently as to how they would actually be done.
Topic archived. No new replies allowed.