js基础算法

实现一个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
class Stack {
constructor() {
this.items = [];
}
// 入栈或者压栈
push(ele) {
this.items.push(ele);
}
// 移除栈顶元素
pop() {
this.items.pop();
}
// 返回栈顶的元素
peek() {
return this.items[this.items.length - 1];
}
// 判断是否为空
isEmpty() {
return this.items.length === 0;
}
// 长度
size() {
return this.item.length;
}
}
function sysConvertToBinary(decimal) {
let stack = new Stack();
let remainder;
while (decimal > 0) {
reminder = decimal % 2;
decimal = Math.floor(decimal / 2);
stack.push(remainder);
}
let str = '';
while(!stack.isEmpth()) {
str += stack.pop();
}
return str;
}
console.log(sysConvertToBinary(101)); // 110011