
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Number of even substrings in a string of digits in C++
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
- Related Articles
- C++ code to count number of even substrings of numeric string
- Sum of individual even and odd digits in a string number using JavaScript
- Counting even decimal value substrings in a binary string in C++
- Find Numbers with Even Number of Digits in Python
- Number of Substrings divisible by 6 in a String of Integers in C++
- Find the Number of Substrings of a String using C++
- Fetch Numbers with Even Number of Digits JavaScript
- Find the sum of digits of a number at even and odd places in C++
- Program to find out number of distinct substrings in a given string in python
- Count odd and even digits in a number in PL/SQL
- Program to find number of different substrings of a string for different queries in Python
- Find the Number of Substrings of One String Present in Other using C++
- Find the Number With Even Sum of Digits using C++
- Rearrange the string to maximize the number of palindromic substrings in C++
- Program to find total sum of all substrings of a number given as string in Python

Advertisements