App下載

JS數(shù)據(jù)結(jié)構(gòu)棧內(nèi)操作:處理十進(jìn)制轉(zhuǎn)二進(jìn)制代碼

猿友 2021-02-20 18:09:47 瀏覽數(shù) (6471)
反饋

微信截圖_20210220093819

計(jì)算十進(jìn)制轉(zhuǎn)換為二進(jìn)制的過(guò)程可以當(dāng)成把每個(gè)計(jì)算后取余的數(shù)字壓入棧內(nèi)的操作

具體實(shí)現(xiàn)過(guò)程如下

//           十進(jìn)制轉(zhuǎn)二進(jìn)制代碼
function dec2bin(decNumber){

    //定義棧
var stack=new Stack()
    //將數(shù)字壓入棧內(nèi)
while(decNumber>0){
    // 1- 獲取余數(shù) 將其壓入棧內(nèi)
    stack.push(decNumber%2)
    // 2- 獲取整除后的結(jié)果 作為下一次取余的數(shù)字
    decNumber=Math.floor(decNumber/2)

}
//               從棧內(nèi)取出

var result=''
while(!stack.isEmpty()){
    //將棧頂數(shù)字依次壓入數(shù)組中 
result+=stack.pop()

}
//返回結(jié)果
return result

}
console.log(dec2bin(1000))
console.log(dec2bin(100))
console.log(dec2bin(10))

微信截圖_20210220093917

手寫(xiě)思路:

1、首先定義一個(gè)函數(shù) 并定義傳入所需轉(zhuǎn)換數(shù)字

2、使用棧結(jié)構(gòu)(此處需提前封裝好棧 功能 如 pop push)

3、循環(huán)判斷(此處為將數(shù)字壓入棧內(nèi)操作) 數(shù)字是否大于0

  • 循環(huán)內(nèi)部 :首先對(duì)傳入的數(shù)字 取余(此處為十進(jìn)制轉(zhuǎn)二進(jìn)制 需除2)然后 將數(shù)字取整后的結(jié)果更新 循環(huán)操作 直到數(shù)字小于等于0

4、首先定義一個(gè)空數(shù)組

5、循環(huán)判斷(此處為將結(jié)果從棧內(nèi)取出操作)棧內(nèi)是否有元素

  • 循環(huán)內(nèi)部 :空數(shù)組 加等 棧內(nèi)每次取出的元素

下面是封裝棧的代碼 可省略

function Stack() {

    //棧 中的一些屬性
    this.items = []
    //棧內(nèi)操作

    //1.將元素壓入棧
    Stack.prototype.push = function (element) {
        this.items.push(element)
    }

    //2.從棧中取出元素
    Stack.prototype.pop = function () {
        return this.items.pop()
    }

    //3.查看一下棧頂元素(不改變棧結(jié)構(gòu))
    Stack.prototype.peek = function () {
        return this.items[this.items.length - 1]
    }

    //4.判斷棧是否為空
    Stack.prototype.isEmpty = function () {
        return this.items.length == 0
    }

    //5.獲取棧中元素個(gè)數(shù)

    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
    }
}


0 人點(diǎn)贊