-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreadBinaryWatch-401.js
62 lines (54 loc) · 1.51 KB
/
readBinaryWatch-401.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// https://leetcode.com/contest/5/problems/binary-watch/
/**
* @param {number} num
* @return {string[]}
*/
const readBinaryWatch = num => {
const hoursObj = {};
const minsObj = {};
const totalObj = {};
function getBinaryNum(n) {
return (n >>> 0).toString(2).split('').filter(i => i === '1').length; // eslint-disable-line no-bitwise
}
function getCombine(a, b) {
const result = [];
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
const hour = a[i];
let min = b[j];
if (b[j] < 10) {
min = `0${b[j]}`;
}
const str = `${hour}:${min}`;
result.push(str);
}
}
return result;
}
for (let i = 0; i < 12; i++) {
if (hoursObj[getBinaryNum(i)] === undefined) {
hoursObj[getBinaryNum(i)] = [];
}
hoursObj[getBinaryNum(i)].push(i);
}
for (let i = 0; i < 60; i++) {
if (minsObj[getBinaryNum(i)] === undefined) {
minsObj[getBinaryNum(i)] = [];
}
minsObj[getBinaryNum(i)].push(i);
}
if (num === 0) return ['0:00'];
for (let i = 0; i < Object.keys(hoursObj).length; i++) {
for (let j = 0; j < Object.keys(minsObj).length; j++) {
const indexSum = i + j;
if (totalObj[indexSum] === undefined) {
totalObj[indexSum] = [];
}
totalObj[indexSum] = totalObj[indexSum].concat(
getCombine(hoursObj[Object.keys(hoursObj)[i]], minsObj[Object.keys(minsObj)[j]])
);
}
}
return totalObj[num] || [];
};
export default readBinaryWatch;