我有这个测试:
Implement an function toReadableString(int) that takes an integer that represents number of seconds
from 00:00:00 and returns a printable string format with AM / PM notation.
For ex.
01:00:00 = 3600
07:00:00 = 25200
toReadableString(3600) should return "1:00AM"
toReadableString(25200) should return "7:00AM"
我的解决方案是:
function padZero(string){
return ("00" + string).slice(-2);
}
function toReadableString(time) {
var hrs = ~~(time / 3600 % 24),
mins = ~~((time % 3600) / 60),
timeType = (hrs>11?"PM":"AM");
return hrs + ":" + padZero(mins) + timeType;
}
但是它无法通过大多数测试用例。测试用例是隐藏的,所以我不知道为什么我没有通过测试。我已经尝试了我能想到的大多数测试用例。有什么想法我的解决方案有什么问题吗?
最佳答案
您的时间在0到24之间(其中0和24实际上是12:00 AM)
function toReadableString(time) {
if (time < 0)
time = 0;
var hrs = ~~(time / 3600 % 24),
mins = ~~((time % 3600) / 60),
timeType = (hrs > 11 ? "PM" : "AM");
if (hrs > 12)
hrs = hrs - 12;
if (hrs == 0)
hrs = 12;
return hrs + ":" + padZero(mins) + timeType;
}