Saturday, June 21, 2014

Time

Problem:

TopCoder Problem Statement - Time

Overview:

Given the number of seconds since midnight, return a formatted String giving the number of hours, minutes, and seconds that have elapsed.

Java Source:
01: public class Time {
02:
03:     public static final int SECONDS_PER_MINUTE = 60;
04:     public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60;
05:
06:     public String whatTime(int seconds) {
07:
08:         /*
09:         Get the whole number of hours that fits into seconds.
10:         Store that as h and then subtract the hours portion
11:          off of seconds.
12:          */
13:         int h = seconds / SECONDS_PER_HOUR;
14:         seconds -= (h * SECONDS_PER_HOUR);
15:
16:         // Repeat to get the number of minutes.
17:         int m = seconds / SECONDS_PER_MINUTE;
18:         seconds -= (m * SECONDS_PER_MINUTE);
19:
20:         // What's left over is the number of seconds.
21:         int s = seconds;
22:
23:         // Create the return String in the appropriate format.
24:         return new String(h + ":" + m + ":" + s);
25:     }
26: }
Notes:

Remember that when dividing ints in Java, the / operator returns the whole number of times that the denominator fits into the numerator. So 10 / 3 = 3.

On line 13, we use this to get the number of hours in the input parameter. The result is multiplied by the number of seconds in an hour, and then subtracted from seconds (line 14).

At that point, the number of seconds left must be less than 1 hour. On line 17 and 17, we repeat the process to get the minute portion. Whatever is left over is the number of seconds.

No comments:

Post a Comment