JS数据结构 栈的应用 10进制转2进制
封装了栈 然后封装了转换函数
找不到哪里错了 显示不出来
下面是代码
//封装栈
function Stack(){
this.items = []
//栈的各种操作
//push压栈 声明在原型里
Stack.prototype.push = function(element){
this.items.push(element)
}
//pop出栈
Stack.prototype.pop = function(){
this.items.pop()
}
//peek查看栈顶元素
Stack.prototype.peek = function(){
return this.items[this.items.length - 1]
}
//isEmpty判断栈是不是为空
Stack.prototype.isEmpty = function(){
return this.items.length == 0
}
//size栈内元素的个数
Stack.prototype.size = function(){
return this.items.length
}
//toString栈内元素合并为字符串 中间以','分隔
Stack.prototype.toString = function(){
let resultString = ''
for(let i = 0; i < this.items.length; i++){
resultString += this.items[i] + ' '
}
return resultString
}
}
// let stack = new Stack()
// stack.push(1)
// stack.push(2)
// alert(stack.items)
//封装 10进制 -> 2进制 函数 dectobin
function dectobin(decNumber){
let stack = new Stack()
//把10进制数 除二 取余 压栈
while(decNumber > 0){
stack.push(decNumber % 2)
decNumber = Math.floor(decNumber / 2)
}
//出栈 把栈里的数字连成字符串 binString
var binString = ''
while(!stack.isEmpty){
binString += stack.pop()
}
return binString
}
//测试 dectobin 函数
alert(dectobin(15))