binary watch
by Laurel Bruggeman
JavaScript
function binaryWatch(str) {
const splits = str.split(':');
const hour = splits[0];
const minute = splits[1];
return toBinaryString(hour, 4) + ':' + toBinaryString(minute, 6);
}
function toBinaryString(num, max) {
const binaryString = [];
for (let i=max - 1; i>=0; i--) {
const powerOf2 = Math.pow(2, i);
if (Math.floor(num / powerOf2) === 1) {
binaryString.push(1);
num -= powerOf2;
} else {
binaryString.push(0);
}
}
const leng = binaryString.length;
for (let i=leng; i<max; i++) {
binaryString.unshift(0);
}
return binaryString.join('');
}
console.log(binaryWatch('01:01'), ' should be 0001:000001');
console.log(binaryWatch('10:30'), ' should be 1010:011110');
console.log(binaryWatch('03:59'), ' should be 0011:111011');