กำหนด string และค่า k นับจำนวนตัวอักษรที่ ASCII value < k และ ≥ k
ตัวอย่าง: str = "TuTorials PoinT", k = 100
Output: น้อยกว่า 100 = 6, มากกว่าหรือเท่า 100 = 9
วิธีแก้ปัญหา
- วนลูปทุกตัวอักษรใน string
- ถ้า
(int)c < kเพิ่มนับน้อยกว่า - มากกว่าหรือเท่า = ความยาว - น้อยกว่า
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int Less_than(string str, int k) {
int count = 0;
for(char c : str)
if(c < k) count++;
return count;
}
int main() {
string str = "TuTorials PoinT";
int k = 100;
int len = str.length();
int less = Less_than(str, k);
int greater = len - less;
cout << "Less than " << k << ": " << less << endl;
cout << "Greater or equal " << k << ": " << greater;
}
Input
"TuTorials PoinT", 100
Output
Less than 100: 6
Greater or equal 100: 9