Add a ton of JS algo snippets (#56)

This commit is contained in:
Yangshun Tay
2017-10-18 17:00:48 +08:00
committed by GitHub
parent d8c3f984e4
commit d9b9d4b5ca
10 changed files with 136 additions and 13 deletions

View File

@ -0,0 +1,19 @@
// Does not handle negative numbers.
function intToBin(number) {
if (number === 0) {
return '0';
}
let res = '';
while (number > 0) {
res = String(number % 2) + res;
number = parseInt(number / 2, 10);
}
return res;
}
console.log(intToBin(0) === 0..toString(2) && 0..toString(2) === '0');
console.log(intToBin(1) === 1..toString(2) && 1..toString(2) === '1');
console.log(intToBin(2) === 2..toString(2) && 2..toString(2) === '10');
console.log(intToBin(3) === 3..toString(2) && 3..toString(2) === '11');
console.log(intToBin(5) === 5..toString(2) && 5..toString(2) === '101');
console.log(intToBin(99) === 99..toString(2) && 99..toString(2) === '1100011');