Count Numbers with N digits which consists of odd number of 0's in C++

C++Server Side ProgrammingProgramming

We are given a number N as input. The goal is to find all N digit numbers that have an odd number of 0’s as digits. The number also could have preceding zeros like in case of N=3 numbers included will be 000,011,012….990.

Let us understand with examples.

Input − N=3

Output − Count of no. with N digits which consists of even number of 0's are − 244

Explanation − All 3 digit numbers would be like −

Smallest will be 000, then 011,012,013,0014…..Highest will be 990.

Input − N=5

Output − Count of no. with N digits which consists of even number of 0's are − 33616

Explanation − All 5 digit numbers would be like −

Smallest will be 00000, then 00011,00012,00013,0014…..Highest will be 99990.

The approach used in the below program is as follows

We will first calculate the total N digit numbers that are T=10N-1. Then calculate all N digit numbers with even 0’s as digits, that is E=10N-8N . The remaining numbers with Odd0’s in digits will be (T-E)/2.

  • Take an integer N as input.

  • Function count_dd(int N) takes N and returns the count of N digit numbers with odd 0’s.

  • Total N digit numbers are total=pow(10,N)-1

  • Total N digit numbers with even 0’s in digit are even=pow(10,N)-pow(8,N).

  • Leftover odd 0’s in digit are odd=(total-even)/2.

  • Return odd as a count of N digit numbers with odd numbers of 0’s.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int count_odd(int N){
   int total = pow(10, N);
   int even = pow(8, N);
   int odd = (total - even) / 2;
   return odd;
}
int main(){
   int N = 4;
   cout<<"Count of Numbers with N digits which consists of odd number of 0's are: "<<count_odd(N);
return 0;
}

Output

If we run the above code it will generate the following output −

Count of Numbers with N digits which consists of odd number of 0's are: 2952
raja
Published on 01-Dec-2020 12:03:10
Advertisements