使用 JavaScript 求最近的时间
问题
我们需要编写一个 JavaScript 函数,它接收一个字符串时间,表示“HH:MM”形式的时间。
我们的函数应该通过重复使用当前数字来形成最近的时间。对数字重复使用的次数没有限制。
例如,如果输入函数的是
输入
const time = '19:34';
输出
const output = '19:39';
输出说明
从数字 1、9、3、4 中选择形成的最近时间为 19:39,它在 5 分钟后出现。它不是 19:33,因为这是在 23 小时 59 分钟后出现的时间。
示例
代码如下 −
const time = '19:34';
const findClosestTime = (time = '') => {
const [a, b, c, d] = [time[0], time[1], time[3], time[4]].map(x =>Number(x));
const sorted = [a, b, c, d].sort((x, y) => x - y)
const d2 = sorted.find(x => x > d)
if (d2 > d) {
return `${a}${b}:${c}${d2}`
}
const c2 = sorted.find(x => x > c && x <= 5)
const min = Math.min(a, b, c, d)
if (c2 > c) {
return `${a}${b}:${c2}${min}`
}
const b2 = sorted.find(x => x > b && a * 10 + x <= 24)
if (b2 > b) {
return `${a}${b2}:${min}${min}`
}
const a2 = sorted.find(x => x > a && x <= 2)
if (a2 > a) {
return `${a2}${min}:${min}${min}`
}
return `${min}${min}:${min}${min}`
};
console.log(findClosestTime(time));输出
19:39
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP