Skip to content

2578. Split With Minimum Sum 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int splitNum(int num) {
    string num1;
    string num2;
    string s = to_string(num);

    ranges::sort(s);

    for (int i = 0; i < s.length(); ++i)
      if (i % 2 == 0)
        num1 += s[i];
      else
        num2 += s[i];

    return stoi(num1) + stoi(num2);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int splitNum(int num) {
    StringBuilder sb1 = new StringBuilder();
    StringBuilder sb2 = new StringBuilder();
    char[] chars = String.valueOf(num).toCharArray();

    Arrays.sort(chars);

    for (int i = 0; i < chars.length; ++i)
      if (i % 2 == 0)
        sb1.append(chars[i]);
      else
        sb2.append(chars[i]);

    return Integer.parseInt(sb1.toString()) + Integer.parseInt(sb2.toString());
  }
}
1
2
3
4
class Solution:
  def splitNum(self, num: int) -> int:
    s = ''.join(sorted(str(num)))
    return sum(map(int, (s[::2], s[1::2])))