// 基于数组封装一个栈
function Stack(){
this.items = [];
// 压栈
Stack.prototype.push = function(element){
return this.items.push(element)
}
// 出栈
Stack.prototype.pop = function(){
return this.items.pop()
}
// 查看栈顶元素
Stack.prototype.peek = function(){
return this.items[this.items.length - 1]
}
// 判断栈是否为空
Stack.prototype.isEmpty = function(){
return this.items.length == 0
}
// 获取栈中元素的个数
Stack.prototype.size = function(){
return this.items.length
}
// toString
Stack.prototype.toString = function(){
let str = '';
for(let i = 0;i < this.items.length;i++){
str += this.items[i] + ' '
}
return str
}
}
let st = new Stack();
st.push(10);
st.push(20);
st.push(30);
st.push(40);
console.log(st);
st.pop()
st.pop()
// console.log(st);
// console.log(st.peek());
// console.log(st.size());
// console.log(st.isEmpty());
// console.log(st.toString());
// 将10进制转2进制
function dec2bin(decNum){
// 实例一个栈对象
var sta = new Stack();
// 循环
while(decNum > 0){
// 将余数压入栈
sta.push(decNum % 2);
// 整数作为下次运行的数字
decNum = Math.floor(decNum / 2);
}
// 从栈中取出0和1,构成二进制
let str = '';
while(sta.size() > 0){
str += sta.pop();
}
return str
}
console.log(dec2bin(10)); // 1010
console.log(dec2bin(100)); // 1100100