1057 数零壹(20 分)
给定一串长度不超过 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 的个数,其间以空格分隔。
输入样例:
输出样例:
代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| #include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
int n = 0;
for (int i = 0; i < s.length(); i++) {
if (isalpha(s[i])) {//判断是否是字母
s[i] = toupper(s[i]);//将小写字母返回大写字母,还有一个tolower是返回小写字母的
n += (s[i] - 'A' + 1);
}
}
int cnt0 = 0, cnt1 = 0;
while (n != 0) {//进制转换。。不行就背下来
if (n % 2 == 0) {
cnt0++;
}
else {
cnt1++;
}
n = n / 2;
}
printf("%d %d", cnt0, cnt1);
return 0;
}
|
二刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| #include <iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int main() {
string s;
getline(cin,s);
int sum = 0,count0=0,count1=0;
vector<int> v;
for(int i = 0;i<s.length();i++){
if(isalpha(s[i])){
sum+=toupper(s[i])-'A'+1;
}
}
while(sum!=0){
v.push_back(sum%2);
sum=sum/2;
}
for(int i = v.size()-1;i>=0;i--){
if(v[i]==1) count1++;
}
count0 = v.size()-count1;
cout<<count0<<" "<<count1;
return 0;
}
|
个人思考:
isalpha()判断是否的字母;
toupper()返回大写字母;
tolower()返回小写字母;