Contents
hide
Codeforces 59A Word Solution
Question
Introduction
String manipulation is a basic skill required in competitive programming. Codeforces Problem 59A titled “Word” features a task that tests whether a competitor can smartly convert cases and handle frequency considerations. This article will discuss the problem statement in detail, followed by a step-wise solution approach along with implementations in C++ and Python.
Problem Statement
Convert the word according to the rule characterized below:
If more than half of the letters are uppercase, convert the whole word into uppercase. Otherwise, convert it into lowercase. In cases where the uppercase letters equal the lowercase letters, convert them to lowercase.
Solution Approach
- Input Reading: Accept the input word as a string.
- Character Counting: TIterate through the string to count the total number of uppercase and lowercase letters.
- Decision Making: Compare the counts to see which case dominates.
- Transformation: Convert the entire string to that case (either all uppercase or lowercase).
- Output the Result: Print the resulting string.
Explanation
- Counting Characters: Both implementations go through a string to tally up the uppercase and lowercase characters.
- Decision Logic: The comparison between upper_count and lower_count determines the case to which the entire string will be transformed
- Transformation: Depending on the comparison, the string is transformed with built-in functions:
- In C++,
std::transform
along with::toupper
or::tolower
is used. - In Python, the string methods
.upper()
and.lower()
are utilized.
- In C++,
Codeforces 59A Word Solution in C++
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string a;
int l=0,u=0;
cin>>a;
for(int i=0;i<a.size();i++)
{
if(a[i]>='a'&& a[i]<='z') {
l++;
}
else
u++;
}
if(l>=u){
for(int i=0;i<a.size();i++)//Codeforces 59A.Word Solution
a[i]=tolower(a[i]);
cout<<a<<endl;
}
else
{
for(int i=0;i<a.size();i++)
{
a[i]=toupper(a[i]);
}
cout<<a<<endl;
}
}
Codeforces 59A Word Solution in C
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_SIZE 1000
int main()
{
char a[MAX_SIZE];
int l = 0, u = 0;
scanf("%s", a);
for (int i = 0; i < strlen(a); i++)
{
if (islower(a[i]))
{
l++;
}
else
{
u++;
}
}
if (l >= u)
{
for (int i = 0; i < strlen(a); i++)
{
a[i] = tolower(a[i]);
}
printf("%s\n", a);
}
else
{
for (int i = 0; i < strlen(a); i++)
{
a[i] = toupper(a[i]);
}
printf("%s\n", a);
}
return 0;
}