carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2160: Minimum Sum of Four Digit Number After Splitting Digits #349

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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.

Example 1:

Input: num = 2932 Output: 52 Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.

Example 2:

Input: num = 4009 Output: 13 Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.

Constraints:

1000 <= num <= 9999

carloscn commented 1 year ago

Analysis

pub fn minimum_sum(num: i32) -> i32
{
    let ret:i32;
    let mut num_dup = num;
    let mut pos:Vec<i32> = vec![];

    while num_dup != 0 {
        pos.push(num_dup %10 as i32);
        num_dup /= 10;
    }

    pos.sort();
    pos.reverse();

    let mut i:usize = 0;
    let mut new1:i32 = 0;
    let mut new2:i32 = 0;
    let mut j1:i32 = 0;
    let mut j2:i32 = 0;
    while i < pos.len() {
        if i & 0x1 == 0 {
            new1 += pos[i] * i32::pow(10, j1 as u32);
            j1 += 1;
        } else {
            new2 += pos[i] * i32::pow(10, j2 as u32);
            j2 += 1;
        }
        i += 1;
    }

    ret = new1 + new2;

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169122 https://github.com/carloscn/structstudy/commit/3b22030fe58d203048fa3d7fa30361c98629cc7a