问题
将一个正整数的,单位为秒的值,转成时间格式
例子
assertEquals("makeReadable(0)", "00:00:00", HumanReadableTime.makeReadable(0));
assertEquals("makeReadable(5)", "00:00:05", HumanReadableTime.makeReadable(5));
assertEquals("makeReadable(60)", "00:01:00", HumanReadableTime.makeReadable(60));
assertEquals("makeReadable(86399)", "23:59:59", HumanReadableTime.makeReadable(86399));
assertEquals("makeReadable(359999)", "99:59:59", HumanReadableTime.makeReadable(359999));
我的代码
package codewars;
public class HumanReadableTime {
private static final Integer MINUTE = 60;
private static final Integer HOUR = MINUTE*60;
public static String makeReadable(int seconds) {
String hourStr = seconds/HOUR < 9? "0"+seconds/HOUR+"" : seconds/HOUR+"";
Integer hourRemain = seconds%HOUR;
String minuteStr = hourRemain/MINUTE < 9? "0"+hourRemain/MINUTE+"" : hourRemain/MINUTE+"";
Integer mimuteRemain = hourRemain%MINUTE;
String secondStr = mimuteRemain < 9? "0"+mimuteRemain+"" : mimuteRemain+"";
return hourStr+":"+minuteStr+":"+secondStr;
}
public static void main(String[] args) {
System.out.println(HumanReadableTime.makeReadable(0));
System.out.println(HumanReadableTime.makeReadable(5));
System.out.println(HumanReadableTime.makeReadable(60));
System.out.println(HumanReadableTime.makeReadable(86399));
System.out.println(HumanReadableTime.makeReadable(359999));
}
}
高手的代码
public class HumanReadableTime {
public static String makeReadable(int seconds) {
return String.format("%02d:%02d:%02d", seconds / 3600, (seconds / 60) % 60, seconds % 60);
}
}
分析
这道题思路很简单,就是除法取余。高手的代码比较简洁,是因为用了String.format对结果格式化输出,学习一下。