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

C++Server Side ProgrammingProgramming

Given a string of digits, we need to find the count of even substrings in it. Let's see an example.

Input

num = "1234"

Output

6

The even substrings that can be formed from the given string are

2
12
4
34
234
1234

Algorithm

  • 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.

Implementation

Following is the implementation of the above algorithm in C++

#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
raja
Published on 03-Jul-2021 05:14:00
Advertisements