js 利用栈结构 实现十进制转二进制

162 阅读1分钟
    // 实现栈结构的基本功能
    function Stack() {
        this.items = [];
        // 1. push(element) 入栈操作
        Stack.prototype.push = function (element) {
            this.items.push(element);
        }
        // 2. pop() 出栈操作
        Stack.prototype.pop = function () {
            return this.items.pop();
        }
        // 3. size() 返回栈数量
        Stack.prototype.size = function () {
            return this.items.length;
        }
        // 4. isEmpty() 是否为空栈
        Stack.prototype.isEmpty = function () {
            return this.items.length === 0;
        }
        // 5. peek()  查看栈顶元素
        Stack.prototype.peek = function () {
            return this.items[this.items.length-1];
        }
        // 6. toString() 方法
        Stack.prototype.toString = function () {
            let result = ''
            for (let i = 0; i < this.items.length; i++){
                let sign = this.items.length-1 === i ? '':','
                result += this.items[i] + sign;
            }
            return result;
        }

    }

    //利用栈结构 实现十进制转二进制
    /*
    *   算法逻辑:
    *   100 / 2 = 500
    *   50 / 2 = 250
    *   25 / 2 = 121
    *   12 / 2 = 60
    *    6 / 2 = 30
    *    3 / 2 = 11
    *    1 / 2 = 01
    */
    function DecToBin( DecNumber = 100 ){
        // 1.利用栈结构 
        let stack = new Stack();

        // 2.循环取余
        while ( DecNumber > 0 ) {
            // 2.1 余数入栈
            stack.push(DecNumber % 2);

            // 2.2 利用  Math.floor() 方法 方便下次循环计算
            DecNumber = Math.floor(DecNumber / 2);
            
            console.log(DecNumber);
        }

        
        let result = '';
        // 3.余数出栈
        // 3.1 如果是空栈,则不进循环
        while ( !stack.isEmpty() ) {
            result += stack.pop();
        }
        console.log(result);
        return Number(result);
    }

    DecToBin(); // 1100100