carloscn / structstudy

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

leetcode2224: Minimum Number of Operations to Convert Time #362

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given two strings current and correct representing two 24-hour times.

24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.

Return the minimum number of operations needed to convert current to correct.

Example 1:

Input: current = "02:30", correct = "04:35" Output: 3 Explanation: We can convert current to correct in 3 operations as follows:

Example 2:

Input: current = "11:00", correct = "11:01" Output: 1 Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1.

Constraints:

current and correct are in the format "HH:MM" current <= correct

carloscn commented 1 year ago

Analysis

fn to_min(times:&str) -> i32
{
    let mut ret:i32 = 0;

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

    ret = s[0] as i32 * 600 + s[1] as i32 * 60 +
          s[3] as i32 * 10 + s[4] as i32;

    return ret;
}

pub fn convert_time(current: &str, correct: &str) -> i32
{
    let mut ret:i32 = 0;
    if current.is_empty() || correct.is_empty() {
        return ret;
    }

    ret = to_min(correct) - to_min(current);
    ret = ret / 60 + ret % 60 / 15 + ret % 15 / 5 + ret % 5;

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169880 https://github.com/carloscn/structstudy/commit/18ee73aaf6ad29bd2b13c6f9902072504b07436b