一、题目
给定一串长度不超过 1 0 5 10^{5} 105的字符串,本题要求你将其中所有英文字母的序号(字母 a-z 对应序号 1-26,不分大小写)相加,得到整数 N,然后再分析一下 N 的二进制表示中有多少 0、多少 1。
例如给定字符串 PAT (Basic),其字母序号之和为:16+1+20+2+1+19+9+3=71,而 71 的二进制是 1000111,即有 3 个 0、4 个 1。
输入格式:
输入在一行中给出长度不超过 [ 0 , 1 0 5 ] [0,10^{5}] [0,105]以回车结束的字符串。
输出格式:
在一行中先后输出 0 的个数和 1 的个数,其间以空格分隔。注意:若字符串中不存在字母,则视为 N 不存在,也就没有 0 和 1。
输入样例:
PAT (Basic)
输出样例:
3 4
二、思路和注意事项
思路:
- 样例中有空格,如果用cin输入,输出的结果为3 3,因为只读进了“pat”.
- 用string存储字符,先把所有字符化成小写再求和。
- 统计的英文字符个数为0时,判“0”直接退出。
- 设置了一个外部函数用于进制转换。该函数在练习题中的
1022 D进制的A+B (20 分) 已经提及到。
三、AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
string dectobin(int n);
int main()
{
int count_0 = 0; //统计 0 个数
int count_1 = 0; //统计 1个数
int count_al = 0;
int i = 0;
int sum = 0;
string str;
getline(cin, str);
for (int i = 0; i <str.length(); i++) //统计字母字符,跳过非字母字符。
{
str[i]=tolower(str[i]);
if (isalpha(str[i]))
{
sum = sum + str[i] - 'a' + 1;
count_al++;
}
else
{
continue;
}
}
if (count_al == 0) //如果没有字母,直接输0
{
cout << "0 0" << endl;
return 0;
}
str = dectobin(sum); //字符串转化为二进制
cout << str << endl;
for (int i = 0; i < str.length(); i++) //统计二进制中的 0和1个数
{
if (str[i] == '0') count_0++;
if (str[i] == '1') count_1++;
}
cout << count_0 << " " << count_1 << endl; //输出结果
}
string dectobin(int sum)
{
string temp = "";
while (sum != 0)
{
temp = temp + to_string(sum % 2);
sum /= 2;
}
reverse(temp.begin(), temp.end());
return temp;
}
结果: