栈的应用

栈的实际应用非常的广泛。在回溯问题中,它可以存储访问过的任务或者路径,撤销的操作等等。
从十进制到二进制
要把十进制转化成二进制,我们可以将该十进制数字和2整出,直到结果是0为止。

function Stack(){
    let items = [];
    // 向栈添加元素
    this.push = function(ele){
        items.push(ele);
    }
    // 从栈移出元素
    this.pop = function(){
        return items.pop();
    }
    // 查看栈顶元素
    this.peek = function(){
        return items[items.length-1];
    }
    // 检查栈是否为空
    this.isEmpty = function(){
        return items.length == 0;
    }
    // 清空栈
    this.clear = function(){
        items = [];
    }
    // 打印栈元素
    this.print = function(){
        console.log(items.toString());
    }
}

function divideByTwo(num){
    var remStack = new Stack(),
        rem,
        bString = '';
    while(num > 0){
        rem = Math.floor(num % 2);
        remStack.push(rem);
        num = Math.floor(num / 2);
    }
    while(!remStack.isEmpty()){
        bString += remStack.pop().toString();
    }
    console.log(bString);
    return bString;
}

测试:

divideByTwo(4);   //100
divideByTwo(10)   //1010

修改算法,把十进制转换成任意进制

function Stack(){
    let items = [];
    // 向栈添加元素
    this.push = function(ele){
        items.push(ele);
    }
    // 从栈移出元素
    this.pop = function(){
        return items.pop();
    }
    // 查看栈顶元素
    this.peek = function(){
        return items[items.length-1];
    }
    // 检查栈是否为空
    this.isEmpty = function(){
        return items.length == 0;
    }
    // 清空栈
    this.clear = function(){
        items = [];
    }
    // 打印栈元素
    this.print = function(){
        console.log(items.toString());
    }
}
function divideByAny(num, base){
    var remStack = new Stack(),
    rem,
    bString = '',
    converts = '0123456789ABCDEF';
    while(num > 0){
        rem = Math.floor(num % base);
        remStack.push(rem);
        num = Math.floor(num / base);
    }
    while(!remStack.isEmpty()){
        bString += converts[remStack.pop()];
    }
    console.log(bString);
    return bString;
}

测试:

divideByAny(8, 2);        //1000
divideByAny(8, 8);        //10
divideByAny(16, 8);       //20
divideByAny(16, 16);      //10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值