Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนคำที่มีผลรวมของค่า ASCII น้อยกว่าและมากกว่า k ใน C++


เราได้รับสตริง str พร้อมประโยคและตัวเลข k เป้าหมายคือการหาจำนวนใน str ที่มีค่า ascii น้อยกว่า k และคำที่มีค่า ascii มากกว่า k

ASCII − รหัสที่ไม่ซ้ำเป็นตัวเลขที่กำหนดให้กับอักขระแต่ละตัวในภาษา

ให้เราเข้าใจด้วยตัวอย่าง

ป้อนข้อมูล − str=“นี่คือ ASCII” k=300

ผลผลิต − การนับจำนวนคำที่มีค่า ASCII รวมกันน้อยกว่า k คือ − 1

จำนวนคำที่มีค่า ASCII มากกว่า k คือ − 2

คำอธิบาย − คำว่า “คือ” มี ascii น้อยกว่า 300 ตัวและอีก 2 ตัว

ป้อนข้อมูล − str=“เซตเซ็ตเซ็ต” k=300

ผลผลิต − จำนวนคำที่มีค่า ASCII น้อยกว่า k คือ − 0

จำนวนคำที่มีค่า ASCII มากกว่า k คือ − 3

คำอธิบาย - ทุกคำเหมือนกันและมี ascii มากกว่า 300

แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้

เราจะสำรวจสตริง str โดยใช้ for loop สำหรับแต่ละคำหลังเว้นวรรค ให้เริ่มเพิ่ม str[i] ให้กับผลรวม ถ้านี่คือ>k จำนวนที่เพิ่มขึ้น

  • ใช้สตริงเป็น str และจำนวนเต็มเป็น k

  • ฟังก์ชัน word_less_greater(string str, int k, int length) รับสตริงและส่งกลับจำนวนคำที่มี ascii น้อยกว่าและมากกว่า k

  • ใช้ temp เป็น 0 สำหรับ ascii ของแต่ละคำใน str.

  • นับเป็น 0 สำหรับการนับคำที่มี ASCII น้อยกว่า k

  • รวมเป็น 0 สำหรับคำทั้งหมดใน k.

  • Traverse str ใช้สำหรับวนซ้ำ

  • สำหรับแต่ละคำหลังช่องว่าง str[i]==‘ ‘ เพิ่มอักขระ str[i] ไปที่ temp หลังจากจบคำ ให้ตรวจสอบว่า temp

  • ถ้าไม่เพิ่มยอดทั้งหมดเท่านั้น

  • ในตอนท้าย การนับมีจำนวนคำที่มี ASCII น้อยกว่า k รวม - นับจะเป็นคำที่มี ascii มากกว่า k.

  • พิมพ์ผล

ตัวอย่าง

#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