Skip to content

Commit 38c9b25

Browse files
authored
Update Smallest String With A Given Numeric Value.java
1 parent 67036e7 commit 38c9b25

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

Medium/Smallest String With A Given Numeric Value.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
class Solution {
22
public String getSmallestString(int n, int k) {
33
StringBuilder sb = new StringBuilder();
4-
for (int idx = 0; idx < n; idx++) {
5-
for (int currChar = 26; currChar > 0; currChar--) {
6-
if (currChar <= k && k - currChar >= (n - idx - 1)) {
7-
sb.append((char) (97 + currChar - 1));
8-
k -= currChar;
9-
break;
10-
}
11-
}
4+
while (k > 0) {
5+
int maxPossible = Math.min(k - n + 1, 26);
6+
sb.append((char) ('a' + maxPossible - 1));
7+
k -= maxPossible;
8+
n--;
129
}
1310
return sb.reverse().toString();
1411
}

0 commit comments

Comments
 (0)