LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.
For example, given num = 2932, you have the following digits: two 2’s, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
Return the minimum possible sum of new1 and new2.
思路
目标情况下new1和new2位数相同。只需要一个variable(res)记录new1和new2的和,和一个variable(position)记录目前process的位数。因为希望更大的数字靠右,从大到小sort num,每一个数字给res加本身乘10的position次方,每两个数字position加一。
答案
class Solution(object):
def minimumSum(self, num):
num = sorted(str(num),reverse=True)
n = len(num)
res = 0
even_iteration = False
position = 0
for i in range(n):
res += int(num[i])*(10**position)
if even_iteration:
position += 1
even_iteration = False
else:
even_iteration = True
return res