栈的封装
//栈 先进后出 //利用js数组来进行封装 function Stack () { this.items = [] //入栈 Stack.prototype.push = function (element) { this.items.push(element) } //出栈 Stack.prototype.pop = function () { this.items.pop() } //查看栈顶元素 Stack.prototype.peek = function () { return this.items[0] } //栈内元素的个数 Stack.prototype.size = function () { return this.items.length } Stack.prototype.isEmpty = function () { return this.items.length == 0 } Stack.prototype.toString = function () { var str = '' for(var i = 0; i < this.items.length; i++) { str += this.items[i] + ' ' } return str } }
//十进制转化为二进制问题
function dec2bin(decimal) {
var stack = new Stack()
while(decimal/2 > 0) {
stack.push(decimal%2)
decimal = Math.floor(decimal/2)
}
var str = ''
while(!stack.isEmpty()) {
str += stack.pop()
}
return str
}
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战