Input: num =4325Output: 59Explanation: We can split 4325 so that num1 is24 and num2 is35, giving a sum of 59. We can prove that 59is indeed the minimal possible sum.
To achieve the minimum sum, distribute the digits of the number as evenly as possible between the two numbers, always assigning the smallest available digit to the number with the smaller current value.
classSolution {
public:int splitNum(int num) {
string s = to_string(num);
sort(s.begin(), s.end());
string a, b;
for (int i =0; i < s.size(); ++i) {
if (i %2==0) a += s[i];
else b += s[i];
}
returnstoi(a) + stoi(b);
}
};
classSolution {
publicintsplitNum(int num) {
char[] s = Integer.toString(num).toCharArray();
Arrays.sort(s);
StringBuilder a =new StringBuilder(), b =new StringBuilder();
for (int i = 0; i < s.length; ++i) {
if (i % 2 == 0) a.append(s[i]);
else b.append(s[i]);
}
return Integer.parseInt(a.toString()) + Integer.parseInt(b.toString());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funsplitNum(num: Int): Int {
val s = num.toString().toCharArray().sorted()
var a = ""var b = ""for (i in s.indices) {
if (i % 2==0) a += s[i]
else b += s[i]
}
return a.toInt() + b.toInt()
}
}
1
2
3
4
5
6
7
8
9
defsplitNum(num: int) -> int:
s = sorted(str(num))
a, b ='', ''for i, d in enumerate(s):
if i %2==0:
a += d
else:
b += d
return int(a) + int(b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnsplit_num(num: i32) -> i32 {
letmut s: Vec<char>= num.to_string().chars().collect();
s.sort();
let (mut a, mut b) = (String::new(), String::new());
for (i, c) in s.iter().enumerate() {
if i %2==0 {
a.push(*c);
} else {
b.push(*c);
}
}
a.parse::<i32>().unwrap() + b.parse::<i32>().unwrap()
}
}