Leetcode 2578. Split With Minimum Sum
You are given a positive integer num. Split it into two non-negative integers num1 and num2 such that:
num1 and num2 equals the original integer num.num1 and num2 should not contain any leading zeroes unless they are zero themselves.Your task is to minimize the sum of the two numbers num1 and num2.
Write a function splitMinSum such that:
public int splitMinSum(int num)
num is a positive integer.num1 and num2 after splitting num as described.num?
num1 and num2 required to be non-zero?
num contains only one digit?
num can’t be split into two non-zero digits meaningfully, we can consider one of the splits as zero. For example, if num = 5, the splits can be num1 = 0 and num2 = 5 or vice-versa.To solve this problem, observe that for minimizing the sum of the two numbers num1 and num2, we need to balance their digit values as closely as possible. The following steps will guide our approach:
num to a String: This helps in easily splitting the number at any position.s, generate all possible splits at each position i where 1 ≤ i ≤ length of s - 1.public class Solution {
public int splitMinSum(int num) {
String numStr = String.valueOf(num);
int minSum = Integer.MAX_VALUE;
for (int i = 1; i < numStr.length(); i++) {
int num1 = Integer.parseInt(numStr.substring(0, i));
int num2 = Integer.parseInt(numStr.substring(i));
int currentSum = num1 + num2;
minSum = Math.min(minSum, currentSum);
}
return minSum;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.splitMinSum(4325)); // Test case
}
}
num.num.This approach effectively balances the simplicity of implementation and efficient computation for typical constraints on num.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?