leetcode每日一题——Split With Minimum Sum

文章目录

一、题目

2578. Split With Minimum Sum

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.

Notes:

It is guaranteed that num does not contain any leading zeros.

The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence of num.

Example 1:

Input: num = 4325

Output: 59

Explanation: We can split 4325 so that num1 is 24 and num2 is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.

Example 2:

Input: num = 687

Output: 75

Explanation: We can split 687 so that num1 is 68 and num2 is 7, which would give an optimal sum of 75.

Constraints:

10 <= num <= 109

二、题解

我的麻烦解法

cpp 复制代码
class Solution {
public:
    int splitNum(int num) {
        vector<int> vals;
        while(num){
            vals.push_back(num % 10);
            num /= 10;
        }
        sort(vals.begin(),vals.end(),greater<int>());
        int a = 0,b = 0;
        int oddCount = 0,evenCount = 0;
        for(int i = 0;i < vals.size();i++){
            if(i % 2 == 0){
                if(oddCount == 0) a += vals[i];
                else a += pow(10,oddCount) * vals[i];
                oddCount++;
            }
            else{
                if(evenCount == 0) b += vals[i];
                else b += pow(10,evenCount) * vals[i];
                evenCount++;
            }
        }
        return a + b;
    }
};

更好的解法

得到num1和num2时从最高位开始乘更好,不要像我上面那样从个位开始乘

cpp 复制代码
class Solution {
public:
    int splitNum(int num) {
        string stnum = to_string(num);
        sort(stnum.begin(), stnum.end());
        int num1 = 0, num2 = 0;
        for (int i = 0; i < stnum.size(); ++i) {
            if (i % 2 == 0) {
                num1 = num1 * 10 + (stnum[i] - '0');
            }
            else {
                num2 = num2 * 10 + (stnum[i] - '0');
            }
        }
        return num1 + num2;
    }
};
相关推荐
Wang's Blog2 分钟前
Java 项目实战: 交友项目 - 入门案例:编写 Dubbo 服务消费者
java·dubbo·交友
IT研究室10 分钟前
最新计算机毕业设计选题推荐-基于spring boot的教育学习平台-网站-文档指导-Java-springboot
java·spring boot·课程设计
余额瞒着我当琳11 分钟前
C++算法学习篇5--二分查找法
c++·学习·算法
亚林瓜子12 分钟前
Spring Boot 集成 ip2region 离线 IP 库实战指南
java·spring boot·后端·ip·ip2region
起个名字费劲死了21 分钟前
基于灰度/形状的2D模板匹配
算法
杜 硕27 分钟前
归并排序详解
数据结构·算法·排序算法
科技观察哨36 分钟前
国产纳米定位平台与精密位移台量产能力图谱(2026):Z轴压电、XYθZ、六自由度并联与光刻/检测/装配选型指南
网络·人工智能·算法
盛世宏博智慧档案39 分钟前
恒湿净化一体机联动开发:档案馆温湿度阈值判断与启停控制实践
java·后端·struts·恒湿机·加湿除湿消毒净化一体机
vipxieliang1 小时前
ValidX 应用于 HR系统员工信息验证:入职、离职、社保数据
java·spring boot·后端
huaweichenai1 小时前
spring boot实现base64上传
java·spring boot·后端