計算數字字串中偶數子字串數量的 C++ 程式碼
假設我們有一個 S 字串,其中有 n 個數字。如果由這個字串表示的數字也是偶數,那麼 S 的子字串稱為偶數。我們必須找出 S 的偶數子字串數。
因此,如果輸入為 S = "1234",那麼輸出將為 6,因為子字串為 2、4、12、34、234、1234。
為了解決這個問題,我們將遵循以下步驟 −
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
示例
讓我們看以下實現以獲得更好的理解 −
#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;
}輸入
1234
輸出
6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP