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)
Average of String Contest
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;
}
Happy Learning – If you require any further information, feel free to contact me.