
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct Frequency Array of Digits in C++
Suppose we have two integers x and n. We have to find the array such that it contains the frequency of index numbers occurring in (x^1, x^2,… x^(n – 1), x^n). So if x = 15 and n = 3, then output will be [0, 1, 2, 2, 0, 3, 0, 1, 0, 0]. As we know that x^1 to x^n, the values are 15, 225 and 3375. So the frequency array is 0, 1, 2, 2, 0, 3, 0, 1, 0, 0
To solve this, we will follow these steps −
Maintain the frequency count array to store the counts of digits 0 to 9.
Traverse through each digit of x^1 to x^n. For each digit add 1 to corresponding index in frequency count array
Display the array.
Example
#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); }
Output
The frequency array is: [0 1 2 2 0 3 0 1 0 0]
Advertisements