Count the number of words having sum of ASCII values less than and greater than k | C ++ implementation of the above approach ; Function to count the words ; Sum of ascii values ; Number of words having sum of ascii less than k ; If character is a space ; Add the ascii value to sum ; Handling the Last word separately ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountWords ( string str , int k ) { int sum = 0 ; int NumberOfWords = 0 ; int counter = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == ' ▁ ' ) { if ( sum < k ) counter ++ ; sum = 0 ; NumberOfWords ++ ; } else sum += str [ i ] ; } NumberOfWords ++ ; if ( sum < k ) counter ++ ; cout << " Number ▁ of ▁ words ▁ having ▁ sum ▁ of ▁ ASCII " " ▁ values ▁ less ▁ than ▁ k ▁ = ▁ " << counter << endl ; cout << " Number ▁ of ▁ words ▁ having ▁ sum ▁ of ▁ ASCII ▁ values " " ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ k ▁ = ▁ " << NumberOfWords - counter ; } int main ( ) { string str = " Learn ▁ how ▁ to ▁ code " ; int k = 400 ; CountWords ( str , k ) ; return 0 ; }