-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.js
More file actions
46 lines (39 loc) · 912 Bytes
/
binary.js
File metadata and controls
46 lines (39 loc) · 912 Bytes
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
const Stack = (function() {
const items = new WeakMap();
class Stack {
constructor(){
items.set(this, []);
}
push(item) {
items.get(this).push(item);
}
pop(){
return items.get(this).pop();
}
isEmpty() {
return items.get(this).length < 1;
}
}
return Stack;
})();
function convertToBinary(d) {
let decimalNumber = Number(d);
if(!isNaN(decimalNumber)){
let _stack = new Stack();
let binaryString = "";
let remainder;
let bin;
while(decimalNumber > 0){
remainder = Math.floor(decimalNumber % 2);
_stack.push(remainder);
decimalNumber = Math.floor(decimalNumber / 2);
}
while(!_stack.isEmpty()) {
bin = _stack.pop();
console.log(bin);
}
return binaryString;
}
return `"${d}" is not a number!`;
}
console.log(convertToBinary("34"));