第一步 通過js 實現一個棧
// 封裝棧
function Stack() {
// 棧的屬性
this.items = []
// 棧的相關操作
// 1. 壓棧
Stack.prototype.push = function(ele) {
this.items.push(ele)
}
// 2. 從棧中取出元素
Stack.prototype.pop = function() {
return this.items.pop()
}
// 3. 查看棧頂元素
Stack.prototype.peek = function() {
return this.items[this.items.length - 1]
}
// 4. 判斷棧是否為空
Stack.prototype.isEmpty = function() {
return this.items.length === 0
}
// 5. 或者棧中元素的數量
Stack.prototype.length = function() {
return this.items.length
}
// 6. toString方法
Stack.prototype.toString = function() {
// return this.items.toString()
var resString = ''
this.items.forEach( i => {
resString += i + ' '
} )
return resString
}
}
第二步 通過棧的形式 實現十進制轉二進制
// 函數: 將十進制轉二進制
function dec2bin(decNumber) {
// 不是數字返回 Err
if(isNaN(decNumber)) throw('decNumber must a number' )
if(decNumber === 0) return '0'
// 取絕對值, 用來處理負數
var absDecNumber = Math.abs(decNumber)
// 1. 定義棧對象
var stack = new Stack()
// 2.循環操作
while(absDecNumber > 0) {
// 2.1 獲取余數 壓入棧中
stack.push(absDecNumber % 2)
// 2.2 獲取整除后的余數結果,作為下一次允許的數字
absDecNumber = Math.floor(absDecNumber / 2)
}
// 3. 從棧中取出 0 和 1
var binaryString = decNumber < 0 ? '-' : ''
while(!stack.isEmpty()) {
binaryString += stack.pop()
}
return binaryString
}