Even sub-string count

In the given input string of digits, find the count of substrings which when convert into integer form even.

Example

Input string : 1234

Output : 6
2, 4, 12, 34, 234, 1234 are the substrings which are even.

Time complexity : O(n)

Algorithm

1. Find all even digits even digits in the input string.

2.    Count the number of sub-strings ending with even digits.

3.    Return final count.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
int EvenSubStrCount(char input_string[])
{
    int length = strlen(input_string);
    int count = 0;
    //Traverse input string
    //If current is even
    //count the number of sub-strings wnding with it
    for (int i = 0; i < length; i++)
    {
        int current = input_string[i] - '0';
        if(current % 2 == 0)
        {
            count = count + (i + 1);
        }
    }
    //return final count
    return count;
}
 
//Main function
int main()
{
    char input_string[] = "1234567";
    cout<<"Even sub-string count is: "<<EvenSubStrCount(input_string)<<endl;
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top