Program to find the number from given holes
Given a number H which represent the total number of holes. The task is to find the smallest number which has that many numbers of holes.
NOTE:
- 0, 4, 6, 9 has 1 holes each and 8 has 2 holes in it.
- The number should not contain leading zeros.
Examples:
Input: H = 1
Output: 0
Input: H = 5
Output: 488
Explanation:
Number which has 5 holes in it is 488. i.e (1 + 2 + 2)
Refer: Count the number of holes in an integer
Approach:
- First of all, Check whether the number of holes given is 0 or 1, if 0 then print 1 and if 1 then print 0.
- If number of holes given is more than 1 then divide the number of holes by 2 and store the remainder in ‘rem’ variable. and quotient in ‘quo’ variable.
- Now, if value of rem variable is equal to 1 then first print 4 once and then print 8 quo number of times.
- Else print 8 only quo number of times.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printNumber( int holes)
{
if (holes == 0)
cout << "1" ;
else if (holes == 1)
cout << "0" ;
else {
int rem = 0, quo = 0;
rem = holes % 2;
quo = holes / 2;
if (rem == 1)
cout << "4" ;
for ( int i = 0; i < quo; i++)
cout << "8" ;
}
}
int main()
{
int holes = 3;
printNumber(holes);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void printNumber( int holes)
{
if (holes == 0 )
System.out.print( "1" );
else if (holes == 1 )
System.out.print( "0" );
else
{
int rem = 0 , quo = 0 ;
rem = holes % 2 ;
quo = holes / 2 ;
if (rem == 1 )
System.out.print( "4" );
for ( int i = 0 ; i < quo; i++)
System.out.print( "8" );
}
}
public static void main (String[] args)
{
int holes = 3 ;
printNumber(holes);
}
}
|
Python3
def printNumber(holes):
if (holes = = 0 ):
print ( "1" )
elif (holes = = 1 ):
print ( "0" , end = "")
else :
rem = 0
quo = 0
rem = holes % 2
quo = holes / / 2
if (rem = = 1 ):
print ( "4" , end = "")
for i in range (quo):
print ( "8" , end = "")
holes = 3
printNumber(holes)
|
C#
using System;
class GFG
{
static void printNumber( int holes)
{
if (holes == 0)
Console.Write ( "1" );
else if (holes == 1)
Console.Write ( "0" );
else
{
int rem = 0, quo = 0;
rem = holes % 2;
quo = holes / 2;
if (rem == 1)
Console.Write ( "4" );
for ( int i = 0; i < quo; i++)
Console.Write ( "8" );
}
}
static public void Main ()
{
int holes = 3;
printNumber(holes);
}
}
|
Javascript
<script>
function printNumber(holes)
{
if (holes == 0)
document.write( "1" );
else if (holes == 1)
document.write( "0" );
else {
let rem = 0, quo = 0;
rem = holes % 2;
quo = parseInt(holes / 2, 10);
if (rem == 1)
document.write( "4" );
for (let i = 0; i < quo; i++)
document.write( "8" );
}
}
let holes = 3;
printNumber(holes);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
13 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...