解題思路
判斷字串是否只含0與1並計數1。
逐字掃描,只接受ASCII字元0及1;遇到其他字元即判為非二進位數。
合法時累加每個字元是否等於1,計數就是1的總數。
輸入保持字串,不做整數轉換,因為需要保留原字串輸出且不應遺失前導零。
時間 O(L),空間 O(L),含原字串。
Step-by-step animation
字串001011的驗證示例
步驟 1 / 3
步驟 1
示例001011,起始計數0。
0
0
1
0
1
1
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string s;
getline(cin, s);
int k = 0;
bool ok = true;
for (char c : s) {
if (c == '1')
k++;
else if (c != '0')
ok = false;
}
if (ok)
cout << "包含1的個數為" << k << '\n';
else
cout << s << " 非二進位數\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。