沿袭上个栈的内容,用数组实现了栈的数据结构的构建:
class Stack {
constructor(arr) {
this.lists = arr
}
//压入栈
push(list){
this.lists.push(list)
}
// 取出栈顶元素
pop(){
return this.lists.pop()
}
// 查看栈顶元素
peek(){
return this.lists[this.lists.length -1]
}
// 判断栈是否为空
isEmpty(){
return this.lists.length === 0
}
// 获取栈中元素个数
size(){
return this.lists.length
}
//toString
toString(){
return this.lists.reduce(
(a,b)=>
a+ (a?'->':'') + (''+b)
,''
)
}
}
用栈实现一个10进制转2进制的程序:
10进制转2进制的原理
var num = 100
num%2 为 0; num = Math.floor(num%2) //50
num%2 为 0; num = Math.floor(num%2) //25
num%2 为 1; num = Math.floor(num%2) //12
num%2 为 0; num = Math.floor(num%2) //6
num%2 为 0; num = Math.floor(num%2) //3
num%2 为 1; num = Math.floor(num%2) //1
num%2 为 1; num = Math.floor(num%2) //0
所有的余数从后往前拼接:1100100
用栈实现
function dec2bin(num) {
const s = new Stack([]);
while (num > 0) {
s.push(num % 2);
num = Math.floor(num / 2);
}
let res = "";
while (!s.isEmpty()) {
res += s.pop();
}
return res;
}
console.log(dec2bin(100));
console.log(dec2bin(1));
console.log(dec2bin(2));
console.log(dec2bin(10));