用 C++ 統計數值大於 X 的子字串數量
給定一個由數字 0 到 9 組成的字串。該字串表示一個十進位制數。目標是找到所有表示十進位制數且大於數字 X 的子字串。條件是子字串不能以 0 開頭。例如,在“2021”中,“02”、“021”、“0”將不被包含。
我們將透過檢查所有子字串的第一個值來實現這一點,如果它大於 0,則從該索引開始建立子字串,並使用 stoi() 將其轉換為整數。如果子字串 > X,則遞增計數。
讓我們透過示例來理解。
輸入 − str=”123” X=12
輸出 − 數值大於 X 的子字串數量為 − 2
說明 大於 12 的子字串是 123 和 23。
輸入 − str=”111” X=100
輸出 − 二進位制字串中偶十進位制值子字串的數量為 − 1
說明 只有 111 大於 100。
下面程式中使用的演算法如下
我們將一個字串 str 作為僅包含數字的字串。
將 str 的長度儲存在 len=str.length() 中
函式 greater_X(string str, int x) 獲取字串及其長度,並返回形成大於 X 的十進位制數的子字串的數量。
使用 FOR 迴圈遍歷字串
從索引 i=0 到 i<len,從左到右讀取。
如果任何 str[i]!=’0’,則表示從它開始的所有子字串都將有效。
從索引 j=1 到 i+j<len,用於子字串的長度。
使用 stoi() 將子字串 str.substr(i,j) 轉換為十進位制。如果它大於 X。遞增計數。
將計數作為結果返回。
示例
#include <bits/stdc++.h> using namespace std; int greater_X(string str, int x){ int count = 0; int len = str.length(); for (int i = 0; i < len; ++i){ if(str[i] != '0'){ for (int j=1; (i + j) <= len; ++j){ if (stoi(str.substr(i, j)) > x){ count++; } } } } return count; } int main(){ string str = "987"; int x = 100; cout<<"Count of number of substrings with numeric value greater than X are: "<<greater_X(str, x); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count of number of substrings with numeric value greater than X are: 1
廣告