C++ 中數字字串的偶數子串數


給定一個數字字串,我們需要找出其中的偶數子串數。我們來看一個示例。

輸入

num = "1234"

輸出

6

可以從給定字串中形成的偶數子串為

2
12
4
34
234
1234

演算法

  • 用數字對字串進行初始化。

  • 將計數初始化為 0.

  • 迭代字串。

    • 透過從當前字元數字中減去字元 0 來獲取當前數字。

    • 檢查數字是偶數還是奇數。

    • 如果當前數字為偶數,則將其索引加 1,並新增到計數中。

  • 返回計數。

實現

以下是 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

更新於:26-Oct-2021

315 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.