/*
【客栈的盘子/月井里的货物,后进先出】
栈顶:最先入口/出口的位置
栈底:最慢最晚出栈的位置
*/
function Stack() { var item = []; //推(将货物推入月井) this.push = function(e) { item.push(e); } //弹(将月井最上方的货物搬出来) this.pop = function() { return item.pop(); } //查(查看月井最上方的货物,但不搬出来) this.peek = function() { return item[item.length - 1]; } //空 this.isEmpty = function() { return item.length == 0; } //量 this.size = function() { return item.length; } //清 this.clear = function() { item = []; } //调 this.price = function() { console.log(item.toString()); } //拼 this.toString = function() { return item.toString(); } }
十进制转二进制。任意进制转二进制
/* 十进制转二进制 原理是将一个大于0的整数,每次都除以2并且记录余数,直到余数为0为止。然后将记录余数叠加即为二进制 */ function divideBy2(decNumber) { var remStack = new Stack(); var rem; var binaryString; while(decNumber > 0) { rem = Math.floor(decNumber % 2); remStack.push(rem); decNumber = Math.floor(decNumber / 2); } if(!remStack.isEmpty()) return remStack.toString(); } function baseConverter(decNumer,base) { var remStack = new Stack(); var rem; var binaryString; var digits = '0123456789ABCDEF'; while(decNumber > 0) { rem = Math.floor(decNumber % base); remStack.push(rem); decNumber = Math.floor(decNumber / base); } if(!remStack.isEmpty()) { binaryString += digits[remStack.pop()]; } return binaryString; }
队列
/* 队列,先进先出 */ function Queue() { var item = []; //推 this.enqueue = function(e) { item.push(e); } //shift this.dequeue = function() { return item.shift(); } //抽 this.front = function() { return item[0]; } //空 this.isEmpty = function() { return item.length == 0; } //量 this.size = function() { return item.length; } //清 this.clear = function() { item = []; } //调 this.price = function() { console.log(item.toString()); } //拼 this.toString = function() { return item.toString(); } }