เราได้รับสตริง str (ประโยค) และตัวเลข k เป้าหมายคือหาจำนวนคำที่มีผลรวมค่า ASCII น้อยกว่า k และมากกว่า k
ตัวอย่าง
อินพุต: str = "This is ASCII", k = 300
เอาต์พุต: น้อยกว่า 300: 1 คำ, มากกว่า 300: 2 คำ
คำอธิบาย: คำ "is" มี ASCII น้อยกว่า 300 อีกสองคำมากกว่า
อินพุต: str = "set set set", k = 300
เอาต์พุต: น้อยกว่า 300: 0 คำ, มากกว่า 300: 3 คำ
แนวทางการแก้ปัญหา
วนลูปอ่านสตริง สะสมค่า ASCII ของแต่ละคำ (คั่นด้วย space) เปรียบเทียบกับ k
การนำไปใช้ (Implementation)
#include <bits/stdc++.h>
using namespace std;
void words_less_greater(string str, int k, int length) {
int temp = 0;
int total = 0;
int count = 0;
for (int i = 0; i < length; ++i) {
if (str[i] == ' ') {
if (temp < k) count++;
temp = 0;
total++;
} else {
temp += str[i];
}
}
total++; // คำสุดท้าย
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;
}
เอาต์พุต
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