May 30, 2021 Article blog
The process of converting decimals to binary can be thought of as an operation in which the remaining numbers from each calculation are pressed into the stack
The implementation process is as follows
// 十进制转二进制代码
function dec2bin(decNumber){
//定义栈
var stack=new Stack()
//将数字压入栈内
while(decNumber>0){
// 1- 获取余数 将其压入栈内
stack.push(decNumber%2)
// 2- 获取整除后的结果 作为下一次取余的数字
decNumber=Math.floor(decNumber/2)
}
// 从栈内取出
var result=''
while(!stack.isEmpty()){
//将栈顶数字依次压入数组中
result+=stack.pop()
}
//返回结果
return result
}
console.log(dec2bin(1000))
console.log(dec2bin(100))
console.log(dec2bin(10))
Handwritten ideas:
1. First define a function and define the required conversion numbers to be passed in
2, the use of stack structure (here need to encapsulate the stack function in advance, such as pop)
3, cycle judgment (in this case, the operation of pressing numbers into the stack) whether the number is greater than 0
4. First define an empty array
5, loop to determine (in this case, the results from the stack to remove the operation) there are elements in the stack
Here's the code for the encapsulation stack that can be omitted
function Stack() {
//栈 中的一些属性
this.items = []
//栈内操作
//1.将元素压入栈
Stack.prototype.push = function (element) {
this.items.push(element)
}
//2.从栈中取出元素
Stack.prototype.pop = function () {
return this.items.pop()
}
//3.查看一下栈顶元素(不改变栈结构)
Stack.prototype.peek = function () {
return this.items[this.items.length - 1]
}
//4.判断栈是否为空
Stack.prototype.isEmpty = function () {
return this.items.length == 0
}
//5.获取栈中元素个数
Stack.prototype.size = function () {
return this.items.length
}
//6.toString方法
Stack.prototype.toString = function () {
var result = ''
for (var i = 0; i < this.items.length; i++) {
result += this.items[i]
}
return result
}
}