function Stack() { var items = []; this.push = function(item) { items.push(item) } this.pop = function() { return items.pop() } this.peek = function() { return items[items.length - 1] } this.isEmpty = function() { return items.length == 0 } this.size = function() { return items.length } this.clear = function() { items = [] } this.printf = function() { console.log(items.toString()) } this.divideBy2 = function(decNumber) { var remStack = new Stack(), rem, binaryString = ‘‘; while (decNumber > 0) { rem = Math.floor(decNumber % 2); remStack.push(rem); decNumber = Math.floor(decNumber / 2) } while (!remStack.isEmpty()) { binaryString += remStack.pop().toString() } return binaryString } } var stacks = new Stack(); console.log(stacks.isEmpty()); stacks.push(5); stacks.push(4); console.log(stacks.peek()); stacks.push(11); console.log(stacks.size()); console.log(stacks.isEmpty()); stacks.push(15); stacks.pop(); console.log(stacks.size()); stacks.printf(); console.log(stacks.divideBy2(33));
时间: 2024-10-07 03:20:55