-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGFG_Second Smallest number.cpp
More file actions
47 lines (41 loc) · 972 Bytes
/
Copy pathGFG_Second Smallest number.cpp
File metadata and controls
47 lines (41 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution{
public:
string secondSmallest(int S, int D){
if(S==1 || D==1) return "-1";
if(S>9*D) return "-1";
if(S==9*D) return "-1";
string ans(D,'0');
int sum=S;
int last=-1;
// First Smallest Number
for(int i=D-1;i>=0;i--)
{
if(sum>9)
{
ans[i]='9';
sum-=9;
}
else if(sum>0)
{
ans[i]='0'+sum;
last=i;
sum=0;
}
else
{
ans[i]='0';
}
}
if(ans[0]=='0')
{
ans[0]='1';
ans[last]-=1;
}
// Second Smallest Number
int l=D-2;
while(ans[l]=='9') l--;
ans[l]+=1;
ans[l+1]-=1;
return ans;
}
};