Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนซับสตริงเลขคู่ในสตริงตัวเลข C++


ให้สตริงตัวเลข หาจำนวนซับสตริงที่เป็นเลขคู่

ตัวอย่าง:

Input: "1234"
Output: 6

ซับสตริงคู่: 2, 12, 4, 34, 234, 1234

อัลกอริทึม

  • count = 0
  • วน i = 0 ถึง len-1:
    • digit = str[i] - '0'
    • ถ้า digit % 2 == 0: count += i + 1
  • คืนค่า count

การเขียนโปรแกรม 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; }

ผลลัพธ์

20