使用javascript的stack数据结构,实现进制转换

function Stack() {
    var items = [];

    this.push = function(element){
        items.push(element);
    }

    this.pop = function(){
        return items.pop();
    }

    this.peek = function() {
        return items[items.length -1];
    }

    this.isEmpty = function() {
        return items.length == 0;
    }

    this.size = function() {
        return items.length;
    }

    this.clear = function(){
        items = [];
    }

    this.print = function() {
        console.log(items.toString());
    }
}

function baseConverter(decNumber, base){
    var remStack = new Stack(),
        rem,
        baseString = '',
        digits = '0123456789ABCDEF';

    while (decNumber > 0){
        rem = Math.floor(decNumber % base);
        remStack.push(rem);
        decNumber = Math.floor(decNumber / base);
    }

    while (!remStack.isEmpty()){
        baseString += digits[remStack.pop()];
    }
    return baseString;
}

console.log(baseConverter(100345, 2));
console.log(baseConverter(100345, 8));
console.log(baseConverter(100345, 16));

使用javascript的stack数据结构,实现进制转换

上一篇:索尼夏普发布财报 日系电子消费企业难言利润


下一篇:Python爬虫入门教程 31-100 36氪(36kr)数据抓取 scrapy