Count numbers having 0 as a digit in C++


We are provided a number N. The goal is to find the numbers that have 0 as digit and are in the range [1,N].

We will do this by traversing numbers from 10 to N ( no need to check from 1 to 9 ) and for each number we will check each digit using a while loop. If any digit is found as zero increment count and move to next number otherwise reduce the number by 10 to check digits until number is >0.

Let’s understand with examples.

Input 

N=11

Output 

Numbers from 1 to N with 0 as digit: 1

Explanation 

Starting from i=10 to i<=11
Only 10 has 0 as a digit. No need to check the range [1,9].

Input 

N=100

Output 

Numbers from 1 to N with 0 as digit: 10

Explanation 

10, 20, 30, 40, 50, 60, 70, 80, 90, 100. Ten numbers have 0 as digits.

Approach used in the below program is as follows

  • We take an integer N.

  • Function haveZero(int n) takes n as parameter and returns count of numbers with 0 as digit

  • Take the initial variable count as 0 for such numbers.

  • Traverse range of numbers using for loop. i=10 to i=n

  • Now for each number num=i, using while loop check if num%10==0, if false divide num by 10 and move to next digit until num>0

  • If true stop further checking, increment count and break while loop.

  • At the end of all loops count will have a total numbers with 0 as digit between 1 to N.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int haveZero(int n){
   int count = 0;
   for (int i = 1; i <= n; i++) {
      int num = i;
      while(num>1){
         int digit=num%10;
         if (digit == 0){
            count++;
            break;
         }
         else
            { num=num/10; }
      }
   }
   return count;
}
int main(){
   int N = 200;
   cout <<"Numbers from 1 to N with 0 as digit: "<<haveZero(N);
   return 0;
}

Output

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

Numbers from 1 to N with 0 as digit: 29

Updated on: 31-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements