In: Computer Science
c++ using recursive no loops (for ,while ..ect)not allowed Write a recursive function ‘bool palindrome(string s)’ that returns true if s is a palindrome and false if not. #5: Write a recursive function 'void reverse(string &word)' that reverses the given input string. string name = "damian"; reverse(name); cout << name << endl; //should display "naimad". #7: Write a function 'int numTwos(int n)' which returns the number of 2's in the base-4 expansion of n. cout << numTwos(2170) << endl; // 3
Check whether string is Palindrome or not code-
#include <iostream>
using namespace std;
bool isPalRec(string str,
int s, int e)
{
if (s == e)
return true;
// If first and last characters do not match
if (str[s] != str[e])
return false;
// If there are more than two characters, check if middle substring is also palindrome or not.
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);
return true;
}
bool isPalindrome(string str)
{
int n = str.length();
// An empty string is considered as palindrome
if (n == 0)
return true;
return isPalRec(str, 0, n - 1);
}
int main()
{
string str;
cin>>str;
if(isPalindrome(str))
cout<<"True";
else
cout<<"False";
return 0;
}
Output
Reverse of string code
#include <iostream>
using namespace std;
void reverse_String(string& s, int n,int i){
if(n<=i)
return;
swap(s[i],s[n]);
reverse_String(s,n-1,i+1);
}
int main() {
string str;
cin>>str;
int n= str.length();
reverse_String(str,n-1,0);
cout<<"reversed string is :"<<str;
}
Output
number of 2's in the base-4 expansion of n code-
#include <iostream>
using namespace std;
int base4(int n)
{
int rem,count=0;
int i = 0;
while (n > 0) {
rem = n % 4;
n = n / 4;
if(rem==2)
count++;
}
return count;
}
int main()
{
int n;
cin>>n;
cout<<base4(n);
return 0;
}
Output
Recursive code
#include <bits/stdc++.h>
using namespace std;
int recusion_base4(int x)
{
if (x == 0)
return 0;
else
return (x % 4 + 10 * recusion_base4(x / 4));
}
int main()
{
int n;
cin>>n;
int ans= recusion_base4(n);
int count=0;
while(ans>0)
{
int rem=ans%10;
ans= ans/10;
if(rem==2)
count++;
}
cout<<count;
return 0;
}
Please upvote my answer