PTA basic 1057 数零壹 (20 分) c++语言实现(g++)

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

鸣谢浙江工业大学之江学院石洗凡老师补充题面说明。

 

 

 

#include <iostream>
#include <string>using namespace std;
int main(){
    int count0{0},count1{0},sum{0},temp;
    string str;
    getline(cin,str);
    for(int i=0;i<str.size();i++){
        if(str[i]>='a'&&str[i]<='z'){
            temp=static_cast<int>(str[i])-static_cast<int>('a')+1;
            sum+=temp;
        }else if(str[i]>='A'&&str[i]<='Z'){
            temp=static_cast<int>(str[i])-static_cast<int>('A')+1;
            sum+=temp;
        }
    }
//    cout <<sum<<endl;
    while(sum){
        temp=sum%2;
        if(temp==0){
            count0++;
        }else{
            count1++;
        }
//        cout << temp<<" ";
        sum/=2;
    }
    cout<<count0<<" "<< count1<<endl;
    return 0;
}

 

posted @ 2021-05-09 20:25  keiiha  阅读(57)  评论(0编辑  收藏  举报