In: Computer Science
C++
1. Write a function decimalToBinary() that takes in a positive integer as a parameter and use as stack to convert the integer to a its corresponding binary representation. Hint: divide the integer by 2.
2. A palindrome is a string of characters (a word, phrase, or sentence) that is the same regardless of whether you read it forward or backward—assuming that you ignore spaces, punctuation, and case. For example, Race car is a palindrome. So is A man, a plan, a canal: Panama. Write a function isPalindrome() that takes a string as a parameter and uses a stack to test whether a string is a palindrome.
3. Suppose that you read a binary string—that is, a string of 0s and 1s—one character at a time. Write a function that use a stack but no arithmetic to see whether the number of 0s is equal to the number of 1s. When these counts are not equal, show which character—0 or 1—occurs most frequently and by how much its count exceeds the other’s.
4. Write a program to test the four functions above.
Code
#include <bits/stdc++.h> //includes the stack and all necessary header diles
using namespace std;
//dispay the binary of a number
void decimalToBinary(int num)
{
stack<int> s; //define a stack
int tnum = num; //copy the number
while (tnum > 0)
{
s.push(tnum % 2);
tnum = tnum / 2;
}
cout << "The binary of " << num << " is : ";
//now print the stack contents
while (!s.empty())
{
cout << s.top();
s.pop();
}
}
//isPalindrome method
void isPalindrome(string s)
{
stack<char> st;
for (int i = 0; i < s.length(); i++)
if (isalnum(s[i]))
st.push(s[i]);
//now check the character
for (int i = 0; i < s.length(); i++)
{
if (!isalnum(s[i]))
continue;
if (tolower(s[i]) != tolower(st.top()))
{
cout << "\n"
<< s << " is not palindrome\n";
return;
}
st.pop();
}
cout << "\n"
<< s << " is palindrome\n";
}
//checkString method
void checkString()
{
//input a string from user
string s;
cout << "\nEnter a binary string : ";
cin >> s;
stack<char> s1, s2;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '0')
s1.push(s[i]);
else
s2.push(s[i]);
}
if (s1.size() > s2.size())
{
cout << "\n0's are more than 1's by " << (s1.size() - s2.size());
}
else if (s2.size() > s1.size())
{
cout << "\n1's are more than 0's by " << (s2.size() - s1.size());
}
else
cout << "\nNumber of 1's and 0's are same";
}
//driver code of the program
int main()
{
//call decimalToBinary() method
decimalToBinary(19);
//call the isPalindrome method
isPalindrome("Race car");
//call checkString method
checkString();
}
Screesnhot
Output