(PAT Basic Level)1057 Number Zero and One

Given a string whose length does not exceed 105, this question requires you to add the serial numbers of all English letters in it (letters a-z correspond to serial numbers 1-26, regardless of case) to get the integer N, and then Analyze how many 0s and 1s there are in the binary representation of N. For example, given the string PAT (Basic), the sum of its letter numbers is: 16+1+20+2+1+19+9+3=71, and the binary number of 71 is 1000111, that is, 3 0, 4 1.

Input format:

Enter a string of length not exceeding 105 characters on a line, terminated by a carriage return.

Output format:

Output the number of 0s and the number of 1s in one line, separated by spaces. Note: If there are no letters in the string, it is considered that N does not exist, and there are no 0 and 1.

Input example:

PAT (Basic)

Output sample:

3 4

Code length limit

16 KB

time limit

200 ms

memory limit

64 MB

Code:

#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;
}

For this question, you should first pay attention to the question requirements: add up and calculate the value of N regardless of the case of English letters, then calculate the binary number corresponding to N and store it in the array binary, and finally traverse the array to output the number of 0s and 1s.

Guess you like

Origin blog.csdn.net/gaogao0305/article/details/127657803