PAT 乙级 1057 数零壹
题目
输入样例:
PAT (Basic)
输出样例:
3 4
**分析:**先将读入的字符串逐个进行字符处理,得到和n,再将n转换为二进制,数出其中0 1 的个数。
源码:
#include<stdio.h>
#include<string.h>
int main()
char shuzu[100200];
gets(shuzu);//??
int n = 0; //n用来记和
for (int i = 0; i < strlen(shuzu); i++) {
if (shuzu[i] <= 'Z' && shuzu[i] >= 'A') {
n = n + shuzu[i] - 'A' + 1;
}
else if (shuzu[i] <= 'z' && shuzu[i] >= 'a') {
n = n + shuzu[i] - 'a' + 1;
}
}
//求二进制
int cnt0 = 0, cnt1 = 0, yushu;
if (n == 0)printf("0 0");
else {
while (n / 2 != 0) {
yushu = n % 2;
n = n / 2;
if (yushu == 0) cnt0++;
else if (yushu == 1) cnt1++;
}
printf("%d %d", cnt0, cnt1 + 1);
//因为在上述循环中最后一步n/2==0时,虽然余数等于1,
//但cnt1没有自加,所以结果要加1
}
return 0;
}