Advertisement
jasonpogi1669

Calculate time in 24 hour format after a minutes using C++

Dec 10th, 2021
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     string s;
  7.     cin >> s;
  8.     int time;
  9.     cin >> time;
  10.     // extract the time to integer (from string)
  11.     int hrs = stoi(s.substr(0, 2));
  12.     int mins = stoi(s.substr(3, 2));
  13.     // calculate the hours that will be added
  14.     if (mins + time >= 60) {
  15.         hrs += ((mins + time) / 60);
  16.     }
  17.     // calculate the final time
  18.     hrs %= 24;
  19.     mins = (mins + time) % 60;
  20.     // convert the integer back to string
  21.     // note: don't forget to place a colon(:) between the hours and minutes
  22.     string ans = (hrs < 10 ? "0" + to_string(hrs) : to_string(hrs));
  23.     ans += (":" + (mins < 10 ? "0" + to_string(mins) : to_string(mins)));
  24.     cout << ans << '\n';
  25.     return 0;
  26. }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement