
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
XOR of Prime Frequencies of Characters in a String in C++
In this problem, we are given a string of characters, our task is to print the XOR of frequencies of characters of the string whose frequency of occurrence is a prime number.
Let’s take an example to understand the problem,
Input − TutorialsPoint
Output −
Here, we will check the frequency of occurrence of each character of the string and then find XOR of all the characters whose frequency is a prime number. For this will create an array of prime frequencies. Then we will store frequencies of characters of a string in a map and then matching with prime frequency array. If a match is found the xor is found, on looping to all elements of the map we can find the required XOR’s.
Example
Program to show the implementation of our solution,
#include <bits/stdc++.h> using namespace std; void findPrimes(bool prime[], int p_size){ prime[0] = false; prime[1] = false; for (int p = 2; p * p <= p_size; p++) { if (prime[p]) { for (int i = p * 2; i <= p_size; i += p) prime[i] = false; } } } int findPrimeXOR(string s){ bool prime[100005]; memset(prime, true, sizeof(prime)); findPrimes(prime, 10005); int i, j; map<char, int> charFreq; for (i = 0; i < s.length(); i++) charFreq[s[i]]++; int result = 0; int flag = 0; for (auto i = charFreq.begin(); i != charFreq.end(); i++) { if (prime[i->second]) { result = result ^ i->second; flag = 1; } } if (!flag) return -1; return result; } int main(){ string s = "tutorialspoint"; cout<<"The XOR of frequencies of character which have prime frequencies is : "; cout<<findPrimeXOR(s); return 0; }
Output
The XOR of frequencies of character which have prime frequencies is : 3
Advertisements