用 C++ 統計包含重複數字的數字的拼寫方式
給定一個包含許多重複數字的數字(作為字串)。目標是找到拼寫它的方法數。例如,112233 可以拼寫為“雙一,雙二,雙三”或“一一,二二,三三”。
我們將透過檢查連續的數字來實現這一點。如果數字是“13”,則只有一種拼寫方式:“一 三”(20)。如果數字是“113”,則有“雙一 三”、“一一 三”兩種方式(21)。因此,方法是計算字串中連續數字的數量,並將 2^(count-1) 乘以之前的結果。
讓我們透過例子來理解。
輸入
num=”11211”
輸出
Count of ways to spell a number with repeated digits are: 4
說明
ways are: 1. One one two one one 2. Double one two one one 3. One one two double one 4. Double one two double one
輸入
num=”2212”
輸出
Count of ways to spell a number with repeated digits are: 2
說明
ways are: 1. Two two one two 2. Double two one two
下面程式中使用的方法如下:
我們使用字串 str 來表示一個數字。
函式 word_spell(string str) 獲取 str 中的數字並返回拼寫它的方法數。
將初始變數 count 設定為 0,表示此類方法的數量。
使用 for 迴圈遍歷 str 中的每個數字。
將變數 temp 作為特定數字的重複次數。如果 str[i]==str[i+1],則增加 temp。
計算 count=count*pow(2,temp-1)
最後返回 count 作為結果。
示例
#include<bits/stdc++.h> using namespace std; long long int word_spell(string str){ long long int count = 1; int len = str.length(); for (int i=0; i<len; i++){ int temp = 1; while(i < len-1 && str[i+1] == str[i]){ temp++; i++; } count = count * pow(2, temp-1); } return count; } int main(){ string str = "222211"; cout<<"Count of ways to spell a number with repeated digits are: "<<word_spell(str); return 0; }
輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count of ways to spell a number with repeated digits are: 16
廣告