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.