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;
    }
};
相关推荐
sheji34166 分钟前
【开题答辩全过程】以 小区物业管理APP为例,包含答辩的问题和答案
java
苦藤新鸡10 分钟前
39.二叉树的直径
算法·leetcode·深度优先
星辰徐哥17 分钟前
Java程序的编译与运行机制
java·开发语言·编译·运行机制
老毛肚17 分钟前
Spring 6.0基于JDB手写定制自己的ROM框架
java·数据库·spring
Sylvia-girl20 分钟前
线程安全问题
java·开发语言·安全
沛沛老爹27 分钟前
Web开发者转型AI安全实战:Agent Skills敏感数据脱敏架构设计
java·开发语言·人工智能·安全·rag·skills
曹轲恒28 分钟前
Java并发包atomic原子操作类
java·开发语言
TracyCoder12331 分钟前
LeetCode Hot100(6/100)——15. 三数之和
算法·leetcode
bubiyoushang88832 分钟前
基于传统材料力学势能法的健康齿轮时变啮合刚度数值分析
人工智能·算法
cyforkk32 分钟前
03、Java 基础硬核复习:流程控制语句的核心逻辑与面试考点
java·开发语言·面试