Count the number of holes in an integer in C++


Given an array of holes[10] containing a number of holes in numbers 0 to 9. The goal is to find the number of holes in an integer number given as input. Given − holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0 }

For Example

Input

number = 239143

Output

Count the number of holes in an integer are: 3

Explanation

We will count holes given in holes[]
239143 ( 1+0+0+2+0+0 )

Input

number = 12345

Output

Count the number of holes in an integer are: 3

Explanation

We will count holes given in holes[]
12345 ( 1+1+0+0+1)

Approach used in the below program is as follows

Simply take each leftmost digit using num%10 and add hole count from holes[num%10] to count. Then reduce number num by 10.

  • Take an integer as input.

  • Initialize holes[] array.

  • Function holes_integer(int number, int holes[]) returns the count of number of holes in an integer.

  • Take the initial count as 0.

  • Traverse till number > 0.

  • Take leftmost digit as temp = number % 10. Add holes[temp] to count.

  • Reduce the number by 10.

  • Return count as result at the end.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int holes_integer(int number, int holes[]){
   int count = 0;
   while (number > 0){
      int temp = number % 10;
      count = count + holes[temp];
      number = number/10;
   }
   return count;
}
int main(){
   int number = 239143;
   int holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0};
   cout<<"Count the number of holes in an integer are: "<<holes_integer(number, holes);
   return 0;
}

Output

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

Count the number of holes in an integer are: 2

Updated on: 05-Jan-2021

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements