2160. 拆分数位后四位数字的最小和 (Minimum Sum of Four Digit Number After Splitting Digits)

题目: 2160. Minimum Sum of Four Digit Number After Splitting Digits (拆分数位后四位数字的最小和)

连接: 2160. Minimum Sum of Four Digit Number After Splitting Digits

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.

给你一个四位 正 整数 num 。请你使用 num 中的 数位 ,将 num 拆成两个新的整数 new1 和 new2 。new1 和 new2 中可以有 前导 0 ,且 num 中 所有 数位都必须使用。

比方说,给你 num = 2932 ,你拥有的数位包括:两个 2 ,一个 9 和一个 3 。一些可能的 [new1, new2] 数对为 [22, 93],[23, 92],[223, 9] 和 [2, 329] 。
请你返回可以得到的 new1 和 new2 的 最小 和。

思路分析

如果两个整数位数不相同,那么将位数较高的整数的最高位添加至位数较低的整数的最高位之前,两个整数之和不会变大。

解释: 假设两个整数的位数分别为 n1, n2 (n1 > n2),该位数为 d,那么变化前,该位数对两数之和的贡献为 d×10^n1;变化后为 d × 10^(n2+1) ≤ d×10^n1

假设考虑的是三位数和一位数的和,那么可以得出两个两位数的和是小于等于一个三个数和一个一位数的和的;因此我们可以得出结论,四位数组成的最小的和是两个两位数的和(此时我们不考虑有0的情况,其实有0 和没有0 是一样的),而两个两位数的和最小是要四位数中两个最小的值分别为两个数的十位数,才能得到最小的值。所以我们只需对四位数从小到大排序即可。

具体实现

class Solution {
    public int minimumSum(int num) {
        int[] digits = new int[4];
        for (int i = 0; i < digits.length; i++) {
            //逐个取出每个位上的数字
            digits[i] = num % 10;
            num /= 10;
        }
        //排序
        Arrays.sort(digits);
        //返回最小两位数的和
        return 10 * (digits[0] + digits[1]) + digits[2] + digits[3];
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值