Cho chuỗi str (câu) và số k. Đếm số từ trong str có tổng giá trị ASCII nhỏ hơn k và lớn hơn k.
Ví dụ
Đầu vào: str = "This is ASCII", k = 300
Đầu ra: Nhỏ hơn: 1 ("is"), Lớn hơn: 2 ("This", "ASCII").
Đầu vào: str = "set set set", k = 300
Đầu ra: Nhỏ hơn: 0, Lớn hơn: 3.
Giải thuật
- Duyệt chuỗi, tính tổng ASCII của từng từ (cách nhau bởi khoảng trắng).
- Khi gặp khoảng trắng hoặc hết chuỗi: so sánh tổng với
k, cập nhật bộ đếm.
Ví dụ triển khai
#include <bits/stdc++.h>
using namespace std;
void words_less_greater(string str, int k, int length) {
int temp = 0, total = 0, count = 0;
for (int i = 0; i < length; ++i) {
if (str[i] == ' ') {
if (temp < k) count++;
temp = 0;
total++;
} else {
temp += str[i];
}
}
total++; // từ cuối cùng
if (temp < k) count++;
cout << "Count of number of words having sum of ASCII values less than k are: " << count;
cout << "\nCount of number of words having sum of ASCII values greater than k are: " << total - count;
}
int main() {
string str = "tutorials point";
int k = 900;
int length = str.length();
words_less_greater(str, k, length);
return 0;
}
Kết quả
Count of number of words having sum of ASCII values less than k are: 1 Count of number of words having sum of ASCII values greater than k are: 1