function Stack(){
this.items=[]
// this.push=function (){} 这种是在每个实例对象上直接建立一个实例对象 而下面那个是在原型上公用一个
//将一个元素压入栈
Stack.prototype.push=function (e){
this.items.push(e)
}
//从栈中取出元素
Stack.prototype.pop=function (){
return this.items.pop()
}
//查看栈顶元素
Stack.prototype.peek=function (){
return this.items[this.items.length-1]}
//判断栈是否为空
Stack.prototype.isEmpty=function (){
return this.items.length==0
}
//获取栈中的个数
Stack.prototype.size=function (){
return Stack.items.length
}
//toString
Stack.prototype.toString=function (){
var reslutstring=' '
for(var i=0;i<this.items.length;i++){
reslutstring=this.items[i]+' '
}
return reslutstring
}
}
function dec2bin(decnumber){
var stack=new Stack()
while(decnumber>0){
stack.push(decnumber%2)
decnumber=Math.floor(decnumber/2) //做一个向下取整
}
//从栈中取出
var binaryString=' '
while(!stack.isEmpty()){
binaryString+=stack.pop()
}
return binaryString
}
console.log(dec2bin(100))
</script>
题目:十进制转换为二进制(用JavaScript实现)
最新推荐文章于 2023-02-27 23:00:53 发布