[LeetCode] Split With Minimum Sum

2578. Split With Minimum Sum

Given a positive integer num, split it into two non-negative integers num1 and num2 such that:

  • The concatenation of num1 and num2 is a permutation of num.
  • In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal to the number of occurrences of that digit in num.
  • num1 and num2 can contain leading zeros.

Return the minimum possible sum of num1 and num2.

Notes:

  • It is guaranteed that num does not contain any leading zeros.
  • The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence of num.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int splitNum(int num) {
long long res = 0, po = 1;
string s = to_string(num);
sort(begin(s), end(s));
while(s.length()) {
if(s.length() == 1) {
res += (s.back() - '0') * po;
s.pop_back();
} else {
res += (s.back() - '0') * po;
s.pop_back();
res += (s.back() - '0') * po;
s.pop_back();
}
po *= 10;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/05/PS/LeetCode/split-with-minimum-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.