假设我们有两个整数x和n。我们必须找到一个数组,使其包含出现在(x ^ 1,x ^ 2,... x ^(n – 1),x ^ n)中的索引编号的频率。因此,如果x = 15且n = 3,则输出将为[0,1,2,2,2,0,3,0,1,0,0]。我们知道x ^ 1到x ^ n的值分别是15、225和3375。所以频率数组是0、1、2、2、0、3、0、1、0、0
为了解决这个问题,我们将遵循以下步骤-
维护频率计数数组以存储数字0到9的计数。
遍历x ^ 1的每个数字到x ^ n。对于每个数字,在频率计数数组中的对应索引处添加1
显示数组。
#include <iostream>
#include <cmath>
using namespace std;
void digitCount(double val, long arr[]) {
while ((long)val > 0) {
long digit = (long)val % 10;
arr[(int)digit]++;
val = (long)val / 10;
}
}
void generateFreqArray(int x, int n) {
long freq_count[10]={0};
for (int i = 1; i <= n; i++){
double val = pow((double)x, (double)i);
digitCount(val, freq_count);
}
cout << "[";
for (int i = 0; i <= 9; i++){
cout << freq_count[i] << " ";
}
cout << "\b]";
}
int main() {
int x = 15, n = 3;
cout << "The frequency array is: ";
generateFreqArray(x, n);
}输出结果
The frequency array is: [0 1 2 2 0 3 0 1 0 0]