Apr 14, 2021 at 2:25am Apr 14, 2021 at 2:25am UTC
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.
Apr 14, 2021 at 5:31am Apr 14, 2021 at 5:31am UTC
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 Apr 14, 2021 at 5:45am Apr 14, 2021 at 5:45am UTC