ให้จำนวน n หลัก และหลักที่ต้องการหลีกเลี่ยง งานคือนับจำนวน n หลักที่ไม่มีหลักนั้นปรากฏ
อินพุต − n = 2, digit = 2
เอาต์พุต − count is 153
คำอธิบาย − เลข 2 หลักที่ไม่มีเลข 2 คือ 10,11,13,14,...,99 รวม 153 ตัว
อินพุต − n = 3, digit = 3
เอาต์พุต − count is 2187
แนวทาง
รับ n และ digit
คำนวณ min = 10^(n-1), max = 10^n
วนลูป min ถึง max-1 ตรวจสอบแต่ละหลักว่าไม่ใช่ digit ที่ห้าม
ตัวอย่าง
#include<bits/stdc++.h>
using namespace std;
int count(int n, int digit){
int r =0, count = 0;
int min = (int)(pow(10, n-1));
int max = (int)(pow(10, n));
for(int i=min; i<max; i++){
int a=i, f=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;
}
เอาต์พุต
Count of 2 digit numbers not having a particular digit 2 is :153