Minimum Sum of Four Digit Number After Splitting Digits
Problem
Given a four-digit number num, split its digits into two new numbers (without leading zeros) so that the sum is minimised. Return the minimum sum.
num = 293252def minimum_sum(num):
d = sorted(str(num))
a = int(d[0] + d[2])
b = int(d[1] + d[3])
return a + b
function minimumSum(num) {
const d = String(num).split("").sort();
const a = Number(d[0] + d[2]);
const b = Number(d[1] + d[3]);
return a + b;
}
class Solution {
public int minimumSum(int num) {
char[] d = Integer.toString(num).toCharArray();
Arrays.sort(d);
int a = (d[0] - '0') * 10 + (d[2] - '0');
int b = (d[1] - '0') * 10 + (d[3] - '0');
return a + b;
}
}
int minimumSum(int num) {
string d = to_string(num);
sort(d.begin(), d.end());
int a = (d[0]-'0')*10 + (d[2]-'0');
int b = (d[1]-'0')*10 + (d[3]-'0');
return a + b;
}
Explanation
To make the sum of two numbers as small as possible, the tens places matter most, because a tens digit counts ten times. So we want the two smallest digits sitting in the tens spots and the two larger digits in the ones spots.
The clean way to arrange that is to sort the four digits ascending. After sorting, d[0] and d[1] are the smallest, and d[2] and d[3] are the largest.
We build two numbers by pairing one small digit with one large digit: a = d[0]d[2] and b = d[1]d[3]. This puts both small digits in tens positions and both large digits in ones positions, then returns a + b.
Example: num = 2932. Sorted digits are [2, 2, 3, 9]. Then a = 23 and b = 29, giving 23 + 29 = 52.
Any other pairing would push a bigger digit into a tens place and raise the total, so this greedy split is optimal.