题目描述
小 K 同学向小 P 同学发送了一个长度为 8 的 01 字符串来玩数字游戏,小 P 同学想要知道字符串中究竟有多少个 1。
注意:01 字符串为每一个字符是 0 或者 1 的字符串,如“101”(不含双引号)为一个长度为 3 的 01 字符串。
输入格式
输入文件只有一行,一个长度为 8 的 01 字符串 s。
输出格式
输出文件只有一行,包含一个整数,即 01 字符串中字符 1 的个数。
输入输出样例
输入 #1复制
00010100
输出 #1复制
2
输入 #2复制
11111111
输出 #2复制
8
这里有多种解法,由于这题出的很水,什么玄学做法都可以过,本人不再一一赘述。本人提供两种做法。
Plan A:字符串
最先写出的代码:
#include<iostream>
using namespace std;
char ch;
int m=0;
int main()
{
while(ch!=EOF)
{
ch=getchar();
if(ch=='1')
{
m++;
}
}
cout<<m;
return 0;
}
优化一下,省掉输入循环:(cin有点慢,不过数据小,没有任何问题)
#include<bits/stdc++.h>
using namespace std;
string s;
int main()
{
cin>>s;
int ans=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='1') ans++;
}
cout<<ans;
}
Pan B:数学
接下来是数论做法:(暴力找规律):
#include<bits/stdc++.h>
using namespace std;
int a;
int main()
{
cin>>a;
cout<<a%9;//学过奥数都懂,不再赘述
}