Reputation: 27
I have been given some integers and I have to count the frequency of a specific digit in the number. example input:
5
447474
228
6664
40
81
The first number says number of integers in the list. I am finding frequency of 4 in this case. I tried to change the integer to an array, but it is not working.
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main() {
int n;
cin>>n;
for (int i=0; i<n; i++)
{
int x;
cin>>x;
int frequency=0;
int t=log10(x);
int arr[t];
for (i=t; i>0; i--)
{
arr[i]=x%10;
x=x/10;
}
for(int i=0; i<t; i++)
{
if(arr[i]==4)
{
frequency++;
}
}
std::cout << frequency << std::endl;
}
return 0;
}
Upvotes: 0
Views: 742
Reputation: 122724
Your code uses VLAs which are not standard C++. See Why aren't variable-length arrays part of the C++ standard?.
log10(x)
is not the number of digits. For example log10(1234) == 3.09131516
but it is 4 digits. Also you are accessing the array out of bounds in the first iteration of the loop: arr[t]
. Valid indices in an array of size t
are 0,1,2,...,t-1
. Trying to access arr[t]
is undefined behavior.
Actually you dont need any array. Instead of storing the digits in an array you can immediately check whether it is a 4
and count.
Even simpler would be to read the user input as a std::string
:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::cout << std::count(input.begin(),input.end(),'4');
}
Perhaps you should add some checks to verify that the user input is actually a valid number. However, also when reading an int
you should validate the input.
Upvotes: 0
Reputation: 5455
No need to create an array, or to determine the number of digits. Just loop until the number reaches zero.
int digitCount(int n, int d) {
if(n < 0) n = -n;
int count = 0;
for(; n != 0; n /= 10)
if(n % 10 == d) count++;
return count;
}
Test:
cout << digitCount(447474, 4) << endl;
cout << digitCount(-447474, 4) << endl;
Output:
4
4
Upvotes: 2