js利用栈实现十进制转二进制数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>栈结构</title>
</head>
<body>
<script>
function Stack(){
//栈中的属性
this.item=[];
//栈的相关操作
//1.将元素压入栈
Stack.prototype.push=function(element){
this.item.push(element)
}
//2.从栈中取出元素
Stack.prototype.pop=function(){
return this.item.pop()
}
//3.查看一下栈顶元素
Stack.prototype.peek=function(){
return this.item[this.item.length -1]
}
//4.判断栈是否为空
Stack.prototype.isEmpty=function(){
return this.item.length === 0
}
//5.获取栈中元素的个数
Stack.prototype.size=function(){
return this.item.length
}
//6.toString方法
Stack.prototype.toString=function(){
//20 10 12 8 7
let resultsString = ''
for(var i =0; i<this.item.length;i++){
resultsString += this.item[i] +' '
}
return resultsString
}
}
//栈的使用
// let s = new Stack();
// s.push(20)
// s.push(10)
// s.push(8)
// s.push(7)
// console.log(s.pop());
// console.log(s.peek());
// console.log(s.isEmpty());
// console.log(s.size());
// console.log(s.toString());
//函数 十进制转二进制
function dec2bin(decNumber){
//1.定义栈对象
let stack = new Stack()
//循环操作
while(decNumber > 0){
//2.1 获取余数 并放入栈中
stack.push(decNumber % 2)
//2.2 获取整除后的结果 向下取整
decNumber = Math.floor(decNumber/2)
}
//3.从栈中取出0和1
var binaryString =''
while(!stack.isEmpty()){
binaryString += stack.pop()
}
return binaryString
}
dec2bin(100)
dec2bin(1000)
console.log(dec2bin(100));
console.log(dec2bin(1000));
</script>
</body>
</html>
打印结果

PS:十进制转二进制推导


浙公网安备 33010602011771号