Average of String - Solution

CoderIndeed
1 minute read
0

Problem : Average of String

You are given a string S. You need to find the floor of average of the string.
Average of string is given by AVG=(sum of ASCII values of all characters)/(length of string)

Hint

Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains a single line of input containing S.

Output:
For each testcase, in a new line, print the floor of average of S.

Constraints:
1 <= T <= 100
1 <= |S| <= 104

Examples:
Input:
2
aaaa
abcd
Output:
97
98

Explanation:
Testcase1: The ASCII value of a is 97. So sum of ASCII values of the given string is 97+97+97+97=388
Now divide the sum by length of string. This gives 388/4=97. Finally, take floor of the average, so floor(97)=97

Solution:

#include<bits/stdc++.h>
using namespace std;

int averageOfString(string s) {
    int sum = 0;
    int length = s.length();
    for (int i = 0; i < length; i++) {
        sum += s[i];
    }
    return floor(sum / length);
}

int main()
{
    int t;
    cin>>t;
    for (int i=0; i<t; ++i)
    {
    string s;
    cin >> s;
    cout << averageOfString(s) << endl;
    }
    return 0;
}

 

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !