// 封裝棧 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 }
原文出處:https://www.cnblogs.com/vant850/p/11621954.htmljavascript