Problem overview
The starter code declares two constants, hours and minutes, which describe how long someone worked on a project. The program must print the same amount of time in seconds.
For example, 1 hour and 2 minutes is 62 minutes, which is 3720 seconds. With the starter values, 13 hours and 47 minutes, the answer is 49620.
Approach
The conversion has two stages, and each one multiplies by 60:
- Express the whole duration in minutes. An hour has 60 minutes, so the total is
hours * 60 + minutes. - Convert minutes to seconds. A minute has 60 seconds, so multiply the total by 60.
The second stage applies to the whole minute count, including the part that came from the hours. That is why the first stage has to be finished before the final multiplication, and why the sum needs parentheses.
Step by step
- Turn hours into minutes with
hours * 60. For 13 hours this is 780. - Add the minutes.
hours * 60 + minutesis 827. Multiplication runs before addition, so no parentheses are needed yet. - Put that sum in parentheses and multiply by 60 to get seconds:
(hours * 60 + minutes) * 60. Without the parentheses, onlyminuteswould be multiplied by 60. - Print the result by passing the expression to
print.
The solution in Swift
let hours = 13
let minutes = 47
print((hours * 60 + minutes) * 60)
The output is:
49620
Swift notes:
- Integers all the way. Both constants are
Int, and so are the literals 60, so the result is anIntand prints without a decimal point. - No overflow worry in practice.
Intis 64 bits on 64-bit platforms, which hold seconds for far more hours than anyone works. In Swift, anIntthat overflows doesn't wrap silently; the program stops with a runtime error. - Parentheses are plain grouping. They don't change any value; they only change the order in which Swift computes the pieces.
Edge cases and common mistakes
- Multiplying only one part.
hours * 60 + minutes * 60converts the hours to minutes, then treats that count as seconds. For 1 hour and 2 minutes it gives 180 instead of 3720. - Forgetting one factor of 60.
hours * 60 + minutesgives minutes, not seconds. For 1 and 2 it prints 62. - Converting each unit separately.
hours * 3600 + minutes * 60is also correct, because an hour has 3600 seconds. For 13 and 47 it also gives 49620. Both forms are fine, as long as every unit is converted. - Zero values. With
hours = 0andminutes = 0, the result is 0. With only minutes, such as 0 and 5, it is 300.
Testing
hours = 1,minutes = 2prints3720.hours = 13,minutes = 47prints49620.hours = 0,minutes = 5prints300.hours = 2,minutes = 0prints7200.
Key takeaways
- Convert in stages: hours to minutes, then minutes to seconds.
- Parentheses make sure the final multiplication applies to the whole sum.
- Check a conversion with a small case you can do by hand, such as 1 hour and 2 minutes.
