PTA(Basic Level)1057.数零壹

给定一串长度不超过 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。

输入格式:

输入在一行中给出长度不超过 105、以回车结束的字符串。

输出格式:

在一行中先后输出 0 的个数和 1 的个数,其间以空格分隔。

输入样例:
PAT (Basic)
输出样例:
3 4
思路
  • 我的思路是读进来,求得字母序号之和,然后转换为二进制的过程求得0、1的个数

  • gets()方法无法通过编译❗

代码
#include<bits/stdc++.h>
using namespace std;
string s;
int count_0 = 0;
int count_1 = 0;

void get_01(int x)
{
	while(x)
	{
		if(x%2==0)
			count_0++;
		else
			count_1++;
		x /= 2;
	}
}

int main()
{
	getline(cin, s);
	int value = 0;
	int tmp;
	for(int i=0;i<s.size();i++)
	{
		if(isalpha(s[i]))
		{
			s[i] = tolower(s[i]);
			tmp = (s[i] - 'a') + 1;
			value += tmp;
		}
	}

	get_01(value);
	cout << count_0 << " " << count_1;
    return 0;
}

引用

https://pintia.cn/problem-sets/994805260223102976/problems/994805270914383872

原文地址:https://www.cnblogs.com/MartinLwx/p/11606672.html