forked from sunbigshan/learnAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackBasedOnObject.js
More file actions
65 lines (60 loc) · 1.17 KB
/
StackBasedOnObject.js
File metadata and controls
65 lines (60 loc) · 1.17 KB
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
63
64
65
class Stack {
constructor() {
this.items = {};
this.count = 0;
}
push(element) {
this.items[this.count++] = element;
}
pop() {
if(this.isEmpty()) {
return undefined;
}
this.count--;
let ret = this.items[this.count];
delete this.items[this.count];
return ret;
}
peek() {
if(this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}
isEmpty() {
return this.count === 0;
}
clear() {
// this.items = {};
// this.count = 0;
while(this.isEmpty()) {
this.pop();
}
}
toString() {
if(this.isEmpty()) {
return '';
}
let objString = `${this.items[0]}`;
for(let i = 1; i < this.count; i++) {
objString += `,${this.items[i]}`;
}
return objString;
}
}
function decimalToBinary(decNumber) {
const remStack = new Stack();
let number = decNumber;
let rem;
let binaryString = '';
while(number > 0) {
rem = Math.floor(number % 2);
remStack.push(rem);
number = Math.floor(number / 2);
}
while(!remStack.isEmpty()) {
binaryString += remStack.pop().toString();
}
return binaryString;
}
console.log(decimalToBinary(11))