📌  相关文章
📜  两个给定时间之间的差

📅  最后修改于: 2021-04-24 05:06:53             🧑  作者: Mango

以字符串“ HH:MM”格式给出两次。这里的“ H”显示小时,“ M”显示分钟。您必须找到这两个字符串在相同字符串格式中的区别。但是,两个给定的字符串都应遵循这些情况。
1)时间1将小于或等于时间2
2)时间可能是0到23。
3)分钟数可能在0到59之间

例子:

Input : s1 = "14:00";
        s2 = "16:45";
Output : result = "2:45"

Input : s1 = "1:04"
        s2 = "13:05"
Output : result = "12:01"

这个想法是先去除结肠。去除冒号后,可以使用简单的数学方法计算时差。

C++
// C++ program to find difference between two
// given times.
#include 
using namespace std;
  
// remove ':' and convert it into an integer
int removeColon(string s)
{
    if (s.size() == 4) 
        s.replace(1, 1, "");
      
    if (s.size() == 5) 
        s.replace(2, 1, "");
      
    return stoi(s);
}
  
// Main function which finds difference
string diff(string s1, string s2)
{
  
    // change string (eg. 2:21 --> 221, 00:23 --> 23)
    int time1 = removeColon(s1);
    int time2 = removeColon(s2);
  
    // difference between hours
    int hourDiff = time2 / 100 - time1 / 100 - 1;
  
    // difference between minutes
    int minDiff = time2 % 100 + (60 - time1 % 100);
  
    if (minDiff >= 60) {
        hourDiff++;
        minDiff = minDiff - 60;
    }
  
    // convert answer again in string with ':'
    string res = to_string(hourDiff) + ':' + to_string(minDiff);
    return res;
}
  
// Driver program to test above functions
int main()
{
    string s1 = "14:00";
    string s2 = "16:45";
    cout << diff(s1, s2) << endl;
    return 0;
}


Python3
# Python 3 program to find difference between two 
# given times. 
  
# Remove ':' and convert it into an integer 
def removeColon(s):
      
    if (len(s) == 4):
        s = s[:1] + s[2:]
      
    if (len(s) == 5): 
        s = s[:2] + s[3:]
      
    return int(s)
  
# Main function which finds difference 
def diff(s1, s2): 
      
    # Change string 
    # (eg. 2:21 --> 221, 00:23 --> 23) 
    time1 = removeColon(s1)
    time2 = removeColon(s2) 
  
    # Difference between hours 
    hourDiff = time2 // 100 - time1 // 100 - 1; 
  
    # Difference between minutes 
    minDiff = time2 % 100 + (60 - time1 % 100) 
  
    if (minDiff >= 60):
        hourDiff += 1
        minDiff = minDiff - 60
  
    # Convert answer again in string with ':' 
    res = str(hourDiff) + ':' + str(minDiff)
      
    return res
  
# Driver code
s1 = "14:00"
s2 = "16:45"
  
print(diff(s1, s2))
  
# This code is contributed by ApurvaRaj


输出:

2:45