Print a number containing K digits with digital root D
Last Updated :
21 Aug, 2022
Given a digital root ‘D’ and number of digits ‘K’. The task is to print a number containing K digits that has its digital root equal to D. Print ‘-1’ if such a number does not exist.
Examples:
Input: D = 4, K = 4
Output: 4000
No. of digits is 4.
Sum of digits is also 4.
Input: D = 0, K = 1
Output: 0
Approach: A key observation to solving this problem is that appending any number of 0s to a number does not change its digital root. Hence D followed by (K-1) 0’s is a simple solution.
Special case when D is 0 and K is not 1 does not have a solution since the only number with digital root 0 is 0 itself.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printNumberWithDR( int k, int d)
{
if (d == 0 && k != 1)
cout << "-1" ;
else {
cout << d;
k--;
while (k--)
cout << "0" ;
}
}
int main()
{
int k = 4, d = 4;
printNumberWithDR(k, d);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void printNumberWithDR( int k, int d)
{
if (d == 0 && k != 1 )
System.out.print( "-1" );
else {
System.out.print(d);
k--;
while (k--> 0 )
System.out.print( "0" );
}
}
public static void main (String[] args) {
int k = 4 , d = 4 ;
printNumberWithDR(k, d);
}
}
|
Python3
def printNumberWithDR( k, d ) :
if d = = 0 and k ! = 1 :
print ( - 1 , end = "")
else :
print (d, end = "")
k - = 1
while k :
print ( 0 ,end = "")
k - = 1
if __name__ = = "__main__" :
k, d = 4 , 4
printNumberWithDR( k, d )
|
C#
using System;
class GFG {
static void printNumberWithDR( int k, int d)
{
if (d == 0 && k != 1)
Console.Write( "-1" );
else {
Console.Write(d);
k--;
while (k-->0)
Console.Write( "0" );
}
}
static public void Main ()
{
int k = 4, d = 4;
printNumberWithDR(k, d);
}
}
|
PHP
<?php
function printNumberWithDR( $k , $d )
{
if ( $d == 0 && $k != 1)
echo "-1" ;
else
{
echo $d ;
$k --;
while ( $k --)
echo "0" ;
}
}
$k = 4;
$d = 4;
printNumberWithDR( $k , $d );
?>
|
Javascript
<script>
function printNumberWithDR(k, d)
{
if (d == 0 && k != 1)
document.write( "-1" );
else
{
document.write(d);
k--;
while (k-->0)
document.write( "0" );
}
}
var k = 4, d = 4;
printNumberWithDR(k, d);
</script>
|
Time complexity: O(K)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...