
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
Count N-Digit Numbers Not Having a Particular Digit in C++
We are given a number let’s say, num and a total number of digits stored in an integer type variable let’s say, digi and the task is to calculate the count of those n digits numbers that can be formed where the given digit is not there.
Input − n = 2, digit = 2
Output − count is 153
Explanation − count of all two digit numbers(n) not having digit 2 is 153 as 10, 11, 13, 14, 15, 16, 17, 18, 19, 30, 31, 33, 34,.......,etc.
Input − n = 3, digit = 3
Output − count is 2187
Explanation − count of all three digit numbers(n) not having digit 3 is 2187 as 10, 11, 13, 14, 15, 16, 17, 18, 19, 30, 31, 33, 34,.......,etc.
Approach used in the below program is as follows
Input the number ‘n’ and the digit as an integer variables
Pass these variables to a function that will perform a count operation
Set two variables min and max value that ‘n’ can reach to. For example, a 2-digit number starts with a minimum value of 10 and ends till 99, similarly, 3-digit numbers start with a minimum of 100 till 999.
Start the loop from min to max
Inside the loop, start while till ‘n’ is greater than 0
Check if the number is there or not. If the number is there don’t perform any operation and if the number isn’t there increase the count by 1.
Example
#include<bits/stdc++.h> using namespace std; int count(int n, int digit){ int r =0; int count = 0; //calculate the min and max of the given number int min = (int)(pow(10, n-1)); int max = (int)(pow(10, n)); //start the loop till max value start from min for(int i=min; i<max; i++){ int a=i; int f=0; //while a is greater than 0 while(a>0){ r=a%10; a=a/10; if(r==digit){ f++; } if(f==0){ count++; } } } return count; } int main(){ int n = 2, digit = 2; cout<<"Count of "<<n<< digit numbers not having a particular digit "<<digit<<" is :"<<count(n, digit); return 0; }
Output
If we run the above code we will get the following output −
Count of 2 digit numbers not having a particular digit 2 is :153