carloscn / structstudy

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

leetcode2562: Find the Array Concatenation Value #419

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a 0-indexed integer array nums.

The concatenation of two numbers is the number formed by concatenating their numerals.

For example, the concatenation of 15, 49 is 1549. The concatenation value of nums is initially equal to 0. Perform this operation until nums becomes empty:

If there exists more than one number in nums, pick the first element and last element in nums respectively and add the value of their concatenation to the concatenation value of nums, then delete the first and last element from nums. If one element exists, add its value to the concatenation value of nums, then delete it. Return the concatenation value of the nums.

Example 1:

Input: nums = [7,52,2,4] Output: 596 Explanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0.

Example 2:

Input: nums = [5,14,13,8,12] Output: 673 Explanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0.

Constraints:

1 <= nums.length <= 1000 1 <= nums[i] <= 104

carloscn commented 1 year ago

Analysis

fn concate_nums(a:i32, b:i32) -> i32
{
    let concatenated_str = format!("{}{}", a, b);

    if let Ok(result) = concatenated_str.parse::<i32>() {
        result
    } else {
        -1
    }
}

pub fn find_the_array_conc_val(nums: Vec<i32>) -> i32
{
    let mut ret:i32 = 0;
    if nums.len() < 1 {
        return ret;
    }

    let mut i:usize = 0;
    let mut j:usize = nums.len() - 1;

    while i < j {
        let e1 = nums[i];
        let e2 = nums[j];
        let e3 = concate_nums(e1, e2);
        ret += e3;
        i += 1;
        j -= 1;
    }
    if (nums.len() & 0x1) == 1 {
        ret += nums[nums.len() / 2];
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1172040 https://github.com/carloscn/structstudy/commit/5934ec12eaaec1ec30de504ec0828a644b1cf527