[LeetCode] Minimum Addition to Make Integer Beautiful

2457. Minimum Addition to Make Integer Beautiful

You are given two positive integers n and target.

An integer is considered beautiful if the sum of its digits is less than or equal to target.

Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.

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
48
class Solution {
long long find(long long n) {
long long res = 0, p = 1;
long long carry = 0;
while(n) {
long long now = carry + n % 10;
carry = now / 10;
now = now % 10;
n /= 10;
if(now) {
res += (10 - now) * p;
carry += 1;
}
p *= 10ll;
}
return res;
}
bool check(long long n, int target) {
long long sum = 0;
while(n) {
sum += n % 10;
n /= 10;
}
return sum <= target;
}
long long __stoll(string& s) {
long long res = 0, p = 1;
for(int i = s.length() - 1; i >= 0; i--) {
res += (s[i] - '0') * p;
p *= 10;
}
return res;
}
public:
long long makeIntegerBeautiful(long long n, int target) {
long long res = find(n);
string s = to_string(res);
while(s.length()) {
string ns = s.substr(1);
long long now = __stoll(ns);
if(check(now + n, target)) res = min(res,now);
s = ns;
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/30/PS/LeetCode/minimum-addition-to-make-integer-beautiful/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.