Number of even substrings in a string of digits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number of even substrings in a string of digits.

Let's see the steps to solve the problem.

  • Initialise the string with digits.

  • Initialise the count to 0.

  • Iterate over the string.

    • Get the current digit by subtracting the char 0 from the current char digit.

    • Check whether the digit is even or not.

    • If the current digit is even, then add it's index plus 1 to the count.

  • Return the count.

Example

Let's see the code.

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int getEvenSubstringsCount(char str[]) {
   int len = strlen(str), count = 0;
   for (int i = 0; i < len; i++) {
      int currentDigit = str[i] - '0';
      if (currentDigit % 2 == 0) {
         count += i + 1;
      }
   }
   return count;
}
int main() {
   char str[] = "12345678";
   cout << getEvenSubstringsCount(str) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

20

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 05:14:00
Advertisements