(PAT 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 的个数,其间以空格分隔。注意:若字符串中不存在字母,则视为 N 不存在,也就没有 0 和 1。

输入样例:

PAT (Basic)

输出样例:

3 4

代码长度限制

16 KB

时间限制

200 ms

内存限制

64 MB

代码:

#include <bits/stdc++.h>
#include <cstring>
#include <string.h>
using namespace std;
int main(){
    string str;
    int i,j=0;
    int N=0;
    int binary[100001];//对应的二进制
    int count_0=0,count_1=0;
    getline(cin,str);
    for(i=0;i<str.length();i++){
        if(str[i]>='a'&&str[i]<='z') N+=str[i]-'a'+1;
        else if(str[i]>='A'&&str[i]<='Z') N+=str[i]-'A'+1;
    }
    //cout<<N<<endl;//检验用
    while(N){
        binary[j++]=(N%2);
        N/=2;
    }//这里输出的binary数组相比实际的输出是反的,但不影响统计0和1的个数
    /*for(i=j-1;i>=0;i--){
        cout<<binary[i];
    }*///这里的代码是对应的对的二进制数输出,检验用 
    for(i=0;i<j;i++){
        if(binary[i]==0)  count_0++;
        else if(binary[i]==1) count_1++;
    }
    cout<<count_0<<" "<<count_1;
    return 0;
}

此题应先注意题目要求:不分英文字母大小写相加计算得到N的值,然后计算N对应的二进制并存入数组binary中,最后遍历数组输出0和1的个数

猜你喜欢

转载自blog.csdn.net/gaogao0305/article/details/127657803
今日推荐