[LeetCode] Largest Integer With Given Digit Sum

4000. Largest Integer With Given Digit Sum

You are given two non-negative integers n and s.

Return the largest integer that has at most n digits and whose sum of digits is s. If no such integer exists, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int largestInteger(int n, int s) {
int res = 0;
for(int i = 0; i < n; i++) {
int d = min(s, 9);
res = res * 10 + d;
s -= d;
}
return s ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/largest-integer-with-given-digit-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.