首页 > 编程语言 > 详细

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

时间:2021-05-09 23:33:17      阅读:30      评论:0      收藏:0      [点我收藏+]

给定一串长度不超过 10?5?? 的字符串,本题要求你将其中所有英文字母的序号(字母 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。

输入格式:

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

输出格式:

在一行中先后输出 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;
}

 

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

原文:https://www.cnblogs.com/ichiha/p/14748747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!