Minimum count of digits required to obtain given Sum
Last Updated :
10 May, 2021
Given an integer N, the task is to find the minimum number of digits required to generate a number having the sum of digits equal to N.
Examples:
Input: N = 18
Output: 2
Explanation:
The number with smallest number of digits having sum of digits equal to 18 is 99.
Input: N = 28
Output: 4
Explanation:
4-digit numbers like 8884, 6877, etc are the smallest in length having sum of digits equal to 28.
Approach: The problem can be solved by the following observations:
- Increment count by 9. Therefore, now count is equal to the number of 9’s in the shortest number. Reduce N to N % 9
- Now, if N exceeds 0, increment count by 1.
- Finally, print count as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void mindigits( int n)
{
if (n % 9 == 0) {
cout << n / 9 << endl;
}
else {
cout << (n / 9) + 1 << endl;
}
}
int main()
{
int n1 = 24;
int n2 = 14;
mindigits(n1);
mindigits(n2);
}
|
Java
import java.util.*;
class Main {
static void mindigits( int n)
{
if (n % 9 == 0 ) {
System.out.println(n / 9 );
}
else {
System.out.println((n / 9 ) + 1 );
}
}
public static void main(String[] args)
{
int n1 = 24 ;
int n2 = 18 ;
mindigits(n1);
mindigits(n2);
}
}
|
Python3
def mindigits(n):
if (n % 9 = = 0 ):
print (n / / 9 );
else :
print ((n / / 9 ) + 1 );
if __name__ = = '__main__' :
n1 = 24 ;
n2 = 18 ;
mindigits(n1);
mindigits(n2);
|
C#
using System;
class GFG{
static void mindigits( int n)
{
if (n % 9 == 0)
{
Console.WriteLine(n / 9);
}
else
{
Console.WriteLine((n / 9) + 1);
}
}
public static void Main(String[] args)
{
int n1 = 24;
int n2 = 18;
mindigits(n1);
mindigits(n2);
}
}
|
Javascript
<script>
function mindigits(n)
{
if (n % 9 == 0) {
document.write(Math.floor(n / 9) + "<br/>" );
}
else {
document.write(Math.floor(n / 9) + 1 + "<br/>" );
}
}
let n1 = 24;
let n2 = 18;
mindigits(n1);
mindigits(n2);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...