
- 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
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
- Related Articles
- Count number of substrings with numeric value greater than X in C++
- Number of even substrings in a string of digits in C++
- Program to count number of palindromic substrings in Python
- Program to count number of homogenous substrings in Python
- C++ code to check phone number can be formed from numeric string
- Count the number of vowels occurring in all the substrings of given string in C++
- C++ code to count number of unread chapters
- Program to count number of distinct substrings in s in Python
- C++ code to count number of weight splits of a number n
- Count Unique Characters of All Substrings of a Given String in C++
- Count of substrings of a binary string containing K ones in C++
- Program to count number of ways we can make a list of values by splitting numeric string in Python
- Program to count number of similar substrings for each query in Python
- Find the Number of Substrings of a String using C++
- C++ code to count number of packs of sheets to be bought

Advertisements