Dhananjay has recently learned about ASCII values. He is very fond of experimenting. With his knowledge of ASCII values and character he has developed a special word and named it Dhananjay's Magical word.
A word that consists of alphabets whose ASCII values is a prime number is a Dhananjay's Magical word. An alphabet is Dhananjay's Magical alphabet if its ASCII value is prime.
Dhananjay's nature is to boast about the things he knows or has learned about. So just to defame his friends he gives a few strings to his friends and asks them to convert them to Dhananjay's Magical word. None of his friends would like to get insulted. Help them to convert the given strings to Dhananjay's Magical Word.
Rules for converting:
1.Each character should be replaced by the nearest Dhananjay's Magical alphabet.
2.If the character is equidistant with 2 Magical alphabets. The one with a lower ASCII value will be considered as its replacement.
Example:
Input: n = 6, s = "AFREEN"
Output: CGSCCO
Approach
C++
#include <bits/stdc++.h>using namespace std;bool isprime(int n){if (n <= 1)return false;for (int i = 2; i <= sqrt(n); i++)if (n % i == 0)return false;return true;}string magicalWord(int n, string s){for (int i = 0; i < n; i++){if (s[i] <= 65)s[i] = 'C';else{int x = s[i];if (!isprime(x)){int x1 = x, x2 = x, res;int flag = 0, flag1 = 0;for (int j = x - 1; j >= 65; j--){if (isprime(j)){x1 = j;flag = 1;break;}}for (int j = x + 1; j <= 122; j++){if (isprime(j)){x2 = j;flag1 = 1;break;}}if (flag1 == 1 && flag == 1){if (abs(x2 - x) < abs(x - x1))res = x2;elseres = x1;}else if (flag == 1)res = x1;elseres = x2;char c = res;s[i] = c;}}}return s;}int main(){int n = 6;string s = "AFREEN";cout << magicalWord(n, s) << "\n";return 0;}
No comments:
Post a Comment