栈结构的应用案例,将10进制转为2进制, 代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>转换进制</title>
</head>
<body>
<script type="text/javascript">
function Stack() {
this.item = []
//进栈
Stack.prototype.push = data => {
return this.item.push(data)
}
//出栈
Stack.prototype.pop = data => {
return this.item.pop()
}
//查询是否为空
Stack.prototype.isEmpty = () => {
return this.item.length === 0
}
//查询第一个
Stack.prototype.peek = () => {
return this.item[this.item.length -1]
}
//查询长度
Stack.prototype.size = () => {
return this.item.length
}
//toString方法
Stack.prototype.toString = () => {
let res = ''
for( let i in this.item) {
res += this.item[i] + ' '
}
return res
}
}
let s = new Stack()
//栈的实用案例
function dec2bin(decNumber) {
if (decNumber) {
while (decNumber > 0){//如果输入的数字大于0, 那么继续循环
console.log(decNumber / 2, decNumber % 2)
s.push(decNumber % 2)//将取余2的数字添加到栈中
decNumber = Math.floor(decNumber / 2)//除2取整
}
let res = ''//创建一个接受出栈的值
while(!s.isEmpty()) {//如果不为空, 则按顺序出栈, 直到为空
res += s.pop()//出战
}
return res//返回最终结果
}
}
//测试代码
console.log(dec2bin(100))
console.log(dec2bin(1024))
</script>
</body>
</html>
效果图如下: