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

In this problem, we are given two integer values, N denoting the count of digits of a number and sum denoting the sum of digits of the number. Our task is to find the largest number with given number of digits and sum of digits.

Let's take an example to understand the problem,

Input : N = 3, sum = 15
Output : 960

## Solution Approach

A simple approach to solve the problem is by traversing all N digit numbers from the largest to smallest. The find the digit sum numbers, if it's equal to sum return the number.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int digitSum(int n){
int sum = 0;
while(n){
sum += n%10;
n = n/10;
}
return sum;
}
int findLargestNumWithSum(int N, int sum){
if (sum == 0){
if(N == 1)
return -1;
else
return -1;
}
if (sum > 9*N){
return -1;
}
int num = 1;
for(int i = 0; i < N; i++)
num *= 10;
while(1){
if(digitSum(num) == sum){
return num;
}
num -- ;
if(num == 0)
return -1;
}
}
int main(){
int sum = 25, N = 3;
cout<<"The largest "<<N<<" digit number with sum "<<sum<<" is "<< findLargestNumWithSum(N, sum);
return 0;
}

## Output

The largest 3 digit number with sum 25 is 997


Another approach to solve the problem is by using Greedy Approach. We will do this by starting from the MSB, placing the highest possible number from sum and subtracting it from the sum.

We will perform this step for N times, we will get the required number. So, if the sum is greater than 9, place 9 to the current digit, if it is less than 9, place sum to the current digit. Do this process, for all digits from MSB to LSB placing digits.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findLargestNumWithSum(int N, int sum){
if (sum == 0){
if(N == 1)
return -1;
else
return -1;
}
if (sum > 9*N){
return -1;
}
int num = 0;
for (int i = 0; i < N; i++){
if (sum >= 9){
num += 9;
sum -= 9;
if(i < (N - 1)){
num *= 10;
}
}
else{
num += sum;
sum = 0;
if( i < (N - 1))
num *= 10;
}
}
return num;
}
int main(){
int sum = 25,
N = 3;
cout<<"The largest "<<N<<" digit number with sum "<<sum<<" is "<<findLargestNumWithSum(N, sum);
return 0;
}

## Output

The largest 3 digit number with sum 25 is 997