
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements