- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google