预期时间和给定时间之间的时间差
给定初始时钟时间h1:m1和当前时钟时间h2:m2 ,表示24 小时制格式的小时和分钟。当前时钟时间h2:m2可能正确也可能不正确。还给出了一个变量 K,它表示经过的小时数。任务是以秒为单位计算延迟,即预期时间和给定时间之间的时间差。
例子 :
Input: h1 = 10, m1 = 12, h2 = 10, m2 = 17, k = 2
Output: 115 minutes
The clock initially displays 10:12. After 2 hours it must show 12:12. But at this point, the clock displays 10:17. Hence, the clock must be lagging by 115 minutes. so the answer is 115.
Input: h1 = 12, m1 = 00, h2 = 12, m2 = 58, k = 1
Output: 2 minutes
The clock initially displays 12:00. After 1 hour it must show 13:00. But at this point, the clock displays 12:58. Hence, the clock must be lagging by 2 minutes. so the answer is 2.
方法:
- 将 h:m 格式的给定时间转换为分钟数。它只是 60*h+m。
- 计算两个计算时间(将 K 小时添加到初始时间)。
- 找出分钟的差异,这将是答案。
下面是上述方法的实现。
C++
// C++ program to calculate clock delay
#include
// Function definition with logic
int lagDuration(int h1, int m1, int h2, int m2, int k)
{
int lag, t1, t2;
// Conversion to minutes
t1 = (h1 + k) * 60 + m1;
// Conversion to minutes
t2 = h2 * 60 + m2;
// Calculating difference
lag = t1 - t2;
return lag;
}
// Driver Code
int main()
{
int h1 = 12, m1 = 0;
int h2 = 12, m2 = 58;
int k = 1;
int lag = lagDuration(h1, m1, h2, m2, k);
printf("Lag = %d minutes", lag);
return 0;
}
Java
// Java program to
// calculate clock delay
class GFG
{
// Function definition
// with logic
static int lagDuration(int h1, int m1,
int h2, int m2,
int k)
{
int lag, t1, t2;
// Conversion to minutes
t1 = (h1 + k) * 60 + m1;
// Conversion to minutes
t2 = h2 * 60 + m2;
// Calculating difference
lag = t1 - t2;
return lag;
}
// Driver Code
public static void main(String args[])
{
int h1 = 12, m1 = 0;
int h2 = 12, m2 = 58;
int k = 1;
int lag = lagDuration(h1, m1, h2, m2, k);
System.out.println("Lag = " + lag +
" minutes");
}
}
// This code is contributed
// by Kirti_Mangal
Python3
# Python3 program to calculate clock delay
# Function definition with logic
def lagDuration(h1, m1, h2, m2, k):
lag, t1, t2 = 0, 0, 0
# Conversion to minutes
t1 = (h1 + k) * 60 + m1
# Conversion to minutes
t2 = h2 * 60 + m2
# Calculating difference
lag = t1 - t2
return lag
# Driver Code
h1, m1 = 12, 0
h2, m2 = 12, 58
k = 1
lag = lagDuration(h1, m1, h2, m2, k)
print("Lag =", lag, "minutes")
# This code has been contributed
# by 29AjayKumar
C#
// C# program to
// calculate clock delay
using System;
class GFG
{
// Function definition
// with logic
static int lagDuration(int h1, int m1,
int h2, int m2,
int k)
{
int lag, t1, t2;
// Conversion to minutes
t1 = (h1 + k) * 60 + m1;
// Conversion to minutes
t2 = h2 * 60 + m2;
// Calculating difference
lag = t1 - t2;
return lag;
}
// Driver Code
public static void Main()
{
int h1 = 12, m1 = 0;
int h2 = 12, m2 = 58;
int k = 1;
int lag = lagDuration(h1, m1, h2, m2, k);
Console.WriteLine("Lag = " + lag +
" minutes");
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
Javascript
Lag = 2 minutes
时间复杂度:O(1)