Human Readable Time

问题

将一个正整数的,单位为秒的值,转成时间格式

例子

    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对结果格式化输出,学习一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值