Riled Solution | CodeChef Puzzle in C++

Problem

Someone is trying to break into Thapar University’s Database and steal sensitive research information. It is now up to us to stop this attack. Fortunately our defence mechanisms have traced the attacks to their source. The fastest way to stop the attacks is to disable the source. So all we need to do is to teach that guy a lesson, by planting a virus in his own system. But before we can do that, we need to break through all the layers of the security he has put around himself. Our sources tell us that the first layer is based on ASCII encryption. We must penetrate through this layer as fast as we can to reach the source…

CodeChef Problem Link

Input

The first line will consist of the total number of test cases T. The next T lines will consist of one string s on each line.

Output

For each test case, output is a single character.

Constraints
  • 2 < s.length
Sample Input
3
abcd
reverse
gear
Sample Output
b
m
g
Solution

The idea is to print the character which is the average of ASCII values of all the characters present in the input string.

Code Implementation

//
//  main.cpp
//  Riled
//
//  Created by Himanshu on 20/02/22.
//

#include <iostream>
#include <string>
using namespace std;

int main() {
    int T, ans = 0;
    cin>>T;
    
    while (T--) {
        string a;
        int sum =0;
        
        cin>>a;
        int n = (int) a.size();
        
        for (int i=0; i<n; i++) {
            sum += a[i];
        }
        
        if (n > 0) {
            ans = sum/n;
        }
        
        printf("%c\n",ans);
    }

    return 0;
}

Time Complexity: O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *