LeetCode知识点总结 - 2160

LeetCode 2160. Minimum Sum of Four Digit Number After Splitting Digits

考点难度
GreedyEasy
题目

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
        
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值