// 实现栈结构的基本功能
function Stack() {
this.items = []
// 1. push(element) 入栈操作
Stack.prototype.push = function (element) {
this.items.push(element)
}
// 2. pop() 出栈操作
Stack.prototype.pop = function () {
return this.items.pop()
}
// 3. size() 返回栈数量
Stack.prototype.size = function () {
return this.items.length
}
// 4. isEmpty() 是否为空栈
Stack.prototype.isEmpty = function () {
return this.items.length === 0
}
// 5. peek() 查看栈顶元素
Stack.prototype.peek = function () {
return this.items[this.items.length-1]
}
// 6. toString() 方法
Stack.prototype.toString = function () {
let result = ''
for (let i = 0
let sign = this.items.length-1 === i ? '':','
result += this.items[i] + sign
}
return result
}
}
//利用栈结构 实现十进制转二进制
/*
* 算法逻辑:
* 100 / 2 = 50 余 0
* 50 / 2 = 25 余 0
* 25 / 2 = 12 余 1
* 12 / 2 = 6 余 0
* 6 / 2 = 3 余 0
* 3 / 2 = 1 余 1
* 1 / 2 = 0 余 1
*/
function DecToBin( DecNumber = 100 ){
// 1.利用栈结构
let stack = new Stack()
// 2.循环取余
while ( DecNumber > 0 ) {
// 2.1 余数入栈
stack.push(DecNumber % 2)
// 2.2 利用 Math.floor() 方法 方便下次循环计算
DecNumber = Math.floor(DecNumber / 2)
console.log(DecNumber)
}
let result = ''
// 3.余数出栈
// 3.1 如果是空栈,则不进循环
while ( !stack.isEmpty() ) {
result += stack.pop()
}
console.log(result)
return Number(result)
}
DecToBin()