//简单应用: //封装函数:将十进制转成二进制(十转二的运算最后倒叙取余的特点符合栈'先进后出') let dec2bin = decNumber => { //1.定义一个栈对象,保存余数 var stack = new Stack() // 2.循环操作 while(decNumber > 0){ // 2.1.获取余数并放入栈中 stack.push(decNumber % 2) // 2.2.获取整除后的结果作为下一次运算的数字(floor:向下取整) decNumber = Math.floor(decNumber / 2) } // 3.从栈中取出0和1 let binaryString = ''; let a = stack.items.length while(stack.items.length != 0){ binaryString += stack.pop(); } return binaryString; } //测试代码 console.log(dec2bin(10)); //103 console.log(dec2bin(100)); //104 console.log(dec2bin(1000)); //105
测试结果: