C++ code to count number of even substrings of numeric string


Suppose we have a string S with n digits. A substring of S is said to be even if the number represented by this string is also even. We have to find the number of even substrings of S.

So, if the input is like S = "1234", then the output will be 6, because the substrings are 2, 4, 12, 34, 234, 1234.

To solve this, we will follow these steps −

a := 0
n := size of S
for initialize i := 0, when i < n, update (increase i by 1), do:
   if S[i] mod 2 is same as 0, then:
      a := a + i + 1
return a

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(string S){
   int a = 0;
   int n = S.size();
   for (int i = 0; i < n; i++){
      if (S[i] % 2 == 0){
         a += i + 1;
      }
   }
   return a;
}
int main(){
   string S = "1234";
   cout << solve(S) << endl;
}

Input

1234

Output

6

Updated on: 15-Mar-2022

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements