顺序扫描长度为 8 的 01 串,遇到字符 '1' 就把计数加一。
OJ: luogu
题目 ID: P5660
难度:入门
标签:模拟字符串
日期: 2026-06-19 09:37
题意
给出一个长度固定为 8 的 01 字符串。
要求统计其中一共有多少个字符 '1'。
思路
这题就是最直接的遍历统计。
从左到右扫一遍字符串,遇到 '1' 就把答案加一。
最直观的写法如下:
cpp
// brute.cpp:直接逐字符统计 01 串里有多少个 '1'。
#include <bits/stdc++.h>
using namespace std;
string s;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> s;
int ans = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] == '1') {
ans++;
}
}
cout << ans << '\n';
return 0;
}因为字符串长度只有 8,甚至不需要考虑任何优化。
代码
cpp
#include <bits/stdc++.h>
using namespace std;
string s;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> s;
int ans = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] == '1') {
ans++;
}
}
cout << ans << '\n';
return 0;
}复杂度
- 时间复杂度:
- 空间复杂度:
这里 n = 8,所以本质上就是常数时间。
总结
题目本身没有隐藏条件,就是简单数一数字符串中 '1' 的个数。