Count the number of holes in an integer
Last Updated :
13 Mar, 2023
Given an integer num, the task is to count the number of holes in that number. The holes in each digit are given below:
Digit |
Number of Holes |
0 |
1 |
1 |
0 |
2 |
0 |
3 |
0 |
4 |
1 |
5 |
0 |
6 |
1 |
7 |
0 |
8 |
2 |
9 |
1 |
Examples:
Input: num = 6457819
Output: 5
Input: num = 2537312
Output: 0
Approach: Initialize holes = 0 and an array hole[] with the values given where hole[i] stores the number of holes in the digit i. Now, for every digit d in num update holes = holes + hole[d]. Print the holes in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int hole[] = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 };
int countHoles( int num)
{
int holes = 0;
while (num > 0) {
int d = num % 10;
holes += hole[d];
num /= 10;
}
return holes;
}
int main()
{
int num = 6457819;
cout << countHoles(num);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int hole[] = { 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 2 , 1 };
static int countHoles( int num)
{
int holes = 0 ;
while (num > 0 )
{
int d = num % 10 ;
holes += hole[d];
num /= 10 ;
}
return holes;
}
public static void main (String[] args)
{
int num = 6457819 ;
System.out.println(countHoles(num));
}
}
|
Python3
hole = [ 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 2 , 1 ]
def countHoles(num):
holes = 0
while (num > 0 ) :
d = num % 10
holes = holes + hole[d]
num = num / / 10
return holes
num = 6457819
print (countHoles(num))
|
C#
using System;
class GFG
{
static int []hole = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 };
static int countHoles( int num)
{
int holes = 0;
while (num > 0)
{
int d = num % 10;
holes += hole[d];
num /= 10;
}
return holes;
}
public static void Main()
{
int num = 6457819;
Console.WriteLine(countHoles(num));
}
}
|
PHP
<?php
$hole = array (1, 0, 0, 0, 1, 0, 1, 0, 2, 1);
function countHoles( $num )
{
global $hole ;
$holes = 0;
while ( $num > 0)
{
$d = $num % 10;
$holes += $hole [ $d ];
$num = (int)( $num / 10);
}
return $holes ;
}
$num = 6457819;
echo countHoles( $num );
?>
|
Javascript
<script>
let hole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ];
function countHoles( num)
{
let holes = 0;
while (num > 0) {
let d = num % 10;
holes += hole[d];
num = Math.floor(num/10);
}
return holes;
}
let num = 6457819;
document.write(countHoles(num));
</script>
|
Time Complexity: O(log10 (num))
Auxiliary Space: O(1), As constant extra space is used.
Share your thoughts in the comments
Please Login to comment...