用 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP