用C++構建一個頻率陣列,該陣列包含從x^1, x^2, ....., x^n獲得的值的數字頻率。
假設我們有兩個整數x和n。我們必須找到一個數組,該陣列包含在(x^1, x^2,… x^(n – 1), x^n)中出現的索引數字的頻率。因此,如果x = 15且n = 3,則輸出將為[0, 1, 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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP