
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
Find Frequency of a Digit in a Number Using C++
Here we will see how to get the frequency of a digit in a number. Suppose a number is like 12452321, the digit D = 2, then the frequency is 3.
To solve this problem, we take the last digit from the number, then check whether this is equal to d or not, if so then increase the counter, then reduce the number by dividing the number by 10. This process will be continued until the number is exhausted.
Example
#include<iostream> using namespace std; int countDigitInNum(long long number, int d) { int count = 0; while(number){ if((number % 10) == d) count++; number /= 10; } return count; } int main () { long long num = 12452321; int d = 2; cout << "Frequency of " << 2 << " in " << num << " is: " << countDigitInNum(num, d); }
Output
Frequency of 2 in 12452321 is: 3
Advertisements