码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-28 12:27:48      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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数据结构,实现进制转换

标签:

原文地址:http://www.cnblogs.com/aguncn/p/5814689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!