carloscn / structstudy

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

leetcode2243: Calculate Digit Sum of a String #366

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a string s consisting of digits and an integer k.

A round can be completed if the length of s is greater than k. In one round, do the following:

Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k. Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13. Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1. Return s after all rounds have been completed.

Example 1:

Input: s = "11111222223", k = 3 Output: "135" Explanation:

Example 2:

Input: s = "00000000", k = 3 Output: "000" Explanation: We divide s into "000", "000", and "00". Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".

Constraints:

1 <= s.length <= 100 2 <= k <= 100 s consists of digits only.

carloscn commented 1 year ago

Analysis

fn round_up(N:i32, S:i32) -> i32
{
    return (((N) + (S) - 1) / (S)) * (S) - N;
}

fn string_sum(s:&Vec<char>, k: i32) -> Vec<char>
{
    let mut i:usize = 0;
    let mut t:Vec<char> = vec![];
    let mut sd: Vec<char> = s.clone();
    let len = round_up(sd.len() as i32, k);

    for _j in 0..len {
        sd.push('0');
    }

    while i < sd.len() {
        let mut sum:i32 = 0;
        for j in 0..k as usize {
            sum += (sd[i + j] as u8 - '0' as u8) as i32;
        }
        i += k as usize;
        if sum >= 10 {
            while sum != 0 {
                t.insert(0, ((sum % 10) as u8 + '0' as u8) as char);
                sum /= 10;
            }
        } else {
            t.push((sum as u8 + '0' as u8) as char);
        }
    }

    return t;
}

pub fn digit_sum(s: &str, k: i32) -> String
{
    if s.len() < 1 {
        return String::new();
    }

    let mut s_vec:Vec<char> = s.chars().collect();

    while s_vec.len() > k as usize {
        s_vec = string_sum(&s_vec, k);
    }

    return s_vec.iter().collect();
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169947 https://github.com/carloscn/structstudy/commit/dee7cfbcd3d7b488d2078d9e09a9045221110883