Input: n =16, target =6Output: 4Explanation: Initially n is16 and its digit sum is1+6=7. After adding 4, n becomes 20 and digit sum becomes 2+0=2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.
Input: n =467, target =6Output: 33Explanation: Initially n is467 and its digit sum is4+6+7=17. After adding 33, n becomes 500 and digit sum becomes 5+0+0=5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.
To make n beautiful, we want to add the smallest x such that the sum of digits of n + x is ≤ target. The greedy way is to round n up to the next number ending with zeros, check the digit sum, and repeat until the sum is ≤ target.
classSolution {
public:longlong makeIntegerBeautiful(longlong n, int target) {
longlong ans =0, base =1;
auto digitSum = [](longlong x) {
int s =0;
while (x) { s += x %10; x /=10; }
return s;
};
while (digitSum(n) > target) {
longlong add = base * (10- n / base %10) % (base *10);
n += add;
ans += add;
base *=10;
}
return ans;
}
};
classSolution {
publiclongmakeIntegerBeautiful(long n, int target) {
long ans = 0, base = 1;
while (digitSum(n) > target) {
long add = base * (10 - (n/base)%10) % (base*10);
n += add;
ans += add;
base *= 10;
}
return ans;
}
privateintdigitSum(long x) {
int s = 0;
while (x > 0) { s += x % 10; x /= 10; }
return s;
}
}
classSolution {
funmakeIntegerBeautiful(n: Long, target: Int): Long {
var ans = 0Lvar base = 1LfundigitSum(x: Long): Int {
var s = 0var y = x
while (y > 0) { s += (y % 10).toInt(); y /=10 }
return s
}
var num = n
while (digitSum(num) > target) {
val add = base * (10 - (num/base)%10) % (base*10)
num += add
ans += add
base *=10 }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defmake_integer_beautiful(n: int, target: int) -> int:
defdigit_sum(x: int) -> int:
s =0while x:
s += x %10 x //=10return s
ans =0 base =1while digit_sum(n) > target:
add = base * (10- (n // base) %10) % (base *10)
n += add
ans += add
base *=10return ans
impl Solution {
pubfnmake_integer_beautiful(n: i64, target: i32) -> i64 {
fndigit_sum(mut x: i64) -> i32 {
letmut s =0;
while x >0 {
s += (x %10) asi32;
x /=10;
}
s
}
letmut ans =0;
letmut base =1;
letmut num = n;
while digit_sum(num) > target {
let add = base * (10- (num/base)%10) % (base*10);
num += add;
ans += add;
base *=10;
}
ans
}
}