# Largest Number Possible

Coding Challenges Streak!

·

2 min read

Table of contents

No heading

No headings in the article.

Given two numbers 'N' and 'S' , find the largest number that can be formed with 'N' digits and whose sum of digits should be equals to 'S'.

Example 1:

Input: N = 2, S = 9 Output: 90 Explaination: It is the biggest number with sum of digits equals to 9. Example 2:

Input: N = 3, S = 20 Output: 992 Explaination: It is the biggest number with sum of digits equals to 20.

Your Task: You do not need to read input or print anything. Your task is to complete the function findLargest() which takes N and S as input parameters and returns the largest possible number. Return -1 if no such number is possible.

Expected Time Complexity: O(N) Exepcted Auxiliary Space: O(1)

Constraints: 1 ≤ N ≤ 104 0 ≤ S ≤ 105

#Code for the above problem // { Driver Code Starts // Initial Template for C++

#include <bits/stdc++.h>
using namespace std;
 // } Driver Code Ends
// User function Template for C++

class Solution{
public:
    string findLargest(int N, int S){
        if(S==0 and N>1 ){
           return "-1";
       }
       int sum=S;
       string ans="";
       while(N>0){
           if(sum>9){
               ans+='9';
               sum-=9;
           }
           else{
               ans+=to_string(sum);
               sum=0;
           }
           N--;
       }
       if(sum==0){
           return ans;
       }
       else{
           return "-1";
       }
   }
};

// { Driver Code Starts.

int main(){
    int t;
    cin>>t;
    while(t--){
        int N, S;
        cin>>N>>S;
        Solution ob;
        cout<<ob.findLargest(N, S)<<"\n";
    }
    return 0;
}  // } Driver Code Ends

Explanation in detail:

  • Basically, they have given N and S where N stands for the number of operations(digits required) to get the sum right ok! Later on, for finding the digits (0-9) which get equated to the value S so we go on checking with the given N value right

  • Step 1: Check if the value of S is >9 or not if yes add it to a string

  • Step 2: decrease the value ans from the S value

  • Step 3: Follow the procedure till the condition fails that is >9 (condition) ok later on go with the next step which is the concatenation of the remaining value to the string ok!

  • Step 4: after adding the remaining value to the string make it S=0 so that if there is a remaining N value the zeros go on adding with it ok!

  • Step 5: That's it finally return the ans ok cool