Free Trial for 3 months and 6 months for student
The task is to find the smallest number with given sum of digits as s and number of digits as d.
print the smallest number if possible, else print -1.
Constraints:
1 ≤ T ≤ 100
1 ≤ s ≤ 100
1 ≤ d ≤ 6
This very simple approach with time complexity is 0.01.
#include <iostream>
using namespace std;
long int sumofdigit(long int n){
long int sum=0;
while(n>0) {
sum=sum+(n%10);
n/=10; }
//cout<<sum<<endl;
return sum;}
int main() {
//code int t; cin>>t;
while(t--) {
int s,d;
cin>>s>>d;
long int f=1,l=9,j=1;
if(s>d*9) {
cout<<-1<<endl;
j=0; }else
for(int i=0;i<d-1;++i) {
f=f*10;
l=(l*10)+9;
}
// cout<<f<<" "<<l<<endl;
for(long int i=f;i<=l;++i) {
long int sum=0;
sum=sumofdigit(i);
if(s==sum) {
cout<<i<<endl;
j=0;
break; }
}
if(j)cout<<-1<<endl;
}
return 0;
}