The function/method calculateTotalTime accepts an argument str. The string str contains multiple integers separated by a space, where each integer ends with a character denoting the unit of time.
d indicates days.
h indicates hours.
m indicates minutes.
s indicates seconds.
The function/method calculateTotalTime must return the total time in days, hours, minutes and seconds.
Your task is to implement the function calculateTotalTime so that the program runs successfully.
The following structure is used to represent the Time and is already defined in the default code (Do not write this definition again in your code).
struct Time
{
int days;
int hours;
int minutes;
int seconds;
};
IMPORTANT: Do not write the main() function as it is already defined.
Example Input/Output 1:
Input:
2h 1d 50m 102s 5d 30s 70m
Output:
6 4 2 12
Explanation:
2h -> 2 hours
1d -> 1 day
50m -> 50 minutes
102s -> 102 seconds
5d -> 5 days
30s -> 30 seconds
70m -> 70 minutes
Total time: 6 days, 4 hours, 2 minutes and 12 seconds.
Example Input/Output 2:
Input:
15d 500s 30h 60s
Output:
16 6 9 20
#include <stdio.h>
#include <stdlib.h>
struct Time {
int days;
int hours;
int minutes;
int seconds;
};
struct Time * calculateTotalTime(char * str) {
int days = 0, hours = 0, minutes = 0, seconds = 0;
strcat(str, " ");
int d = 0, h = 0, m = 0, s = 0;
int num = 0;
for (int i = 0; i < strlen(str); i++) {
char c = str[i];
if (str[i] == ' ') {
if (d == 1) days += num;
if (h == 1) hours += num;
if (m == 1) minutes += num;
if (s == 1) seconds += num;
d = h = m = s = 0;
num = 0;
}
if (isdigit(c)) num = (num * 10) + (int)(c - '0');
if (c == 'd') d++;
if (c == 'h') h++;
if (c == 'm') m++;
if (c == 's') s++;
}
minutes += seconds / 60;
seconds %= 60;
hours += minutes / 60;
minutes %= 60;
days += hours / 24;
hours %= 24;
struct Time * t = (struct Time * ) malloc(sizeof(struct Time));
t -> days = days;
t -> hours = hours;
t -> minutes = minutes;
t -> seconds = seconds;
return t;
}
int main() {
char str[101];
scanf("%[^n]", str);
struct Time * time = calculateTotalTime(str);
if (time == NULL) {
printf("Time is not formedn");
}
printf("%d %d %d %d", time -> days, time -> hours, time -> minutes, time -> seconds);
return 0;
}
Leave a Reply