# Find smallest number with given number of digits and sum of digits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two values that are the sum (denoting the sum of digits) and digit (denoting the number of digits). Our task is to find the smallest number with a given number of digits and sum of digits.

Let’s take an example to understand the problem,

## Input

sum = 15, dgiti = 2

## Output

69

## Explanation

All 2 digits numbers with sum 15 are : 69, 78, 87, 96.

## Solution Approach

A simple solution to the problem is by considering all the numbers with digit count as digit and find the smallest number whose sum of digit is equal to the sum.

An efficient solution is using the greedy approach. We will create the number by filling the elements from the last digit i.e. the LSB of the number. We will consider the largest possible element for LSB and then go for the next position.

We will try to keep the LSB as large as possible and MSB as small as possible.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
void findSmallestNumWithSum(int digit, int sum) {
if (sum == 0) {
if(digit == 1)
cout<<"Smallest number is 0";
else
cout<<"Smallest number with sum cannot be found";
return ;
}
if (sum > 9*digit) {
cout<<"Smallest number with sum cannot be found";
return ;
}
int number[digit];
sum -= 1;
for (int i = digit-1; i>0; i--) {
if (sum > 9) {
number[i] = 9;
sum -= 9;
} else {
number[i] = sum;
sum = 0;
}
}
number = sum + 1;
cout<<"Smallest number is ";
for (int i=0; i<digit; i++)
cout<<number[i];
}
int main() {
int sum = 15, digit = 3;
findSmallestNumWithSum(digit, sum);
return 0;
}

## Output

Smallest number is 159