LeetCode 2578. Split With Minimum Sum
考点 | 难度 |
---|---|
Greedy | Easy |
题目
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.
思路
排序,最小的是第一个数的most significant digit,第二小的是第二个数的most significant digit,以此类推。
答案
class Solution(object):
def splitNum(self, num):
a, b = [], []
for i, c in enumerate(sorted(str(num))):
(a if i % 2 == 0 else b).append(c)
return int(''.join(a)) + int(''.join(b))