JavaScript用栈的思想实现数制转换

可以利用栈将一个数字从一种数制转换成另一种数制。假设想将数字n转换为以b为基数的数字,实现转换的算法如下:

  1. 最高位为 n%b ,将此位压入栈。
  2. 使用 n/b 代替n。
  3. 重复步骤1和2,直到n等于0,且没有余数。
  4. 持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后的数字的字符串形式。
<script>
    function Stack() {
        this.dataStore = [];
        this.top = 0;
        this.push = push;
        this.pop = pop;
        this.peek = peek;
        this.clear = clear;
        this.length = length;
    }

    function push(element) {
        this.dataStore[this.top++] = element;
    }

    function peek() {
        return this.dataStore[this.top-1];
    }

    function pop() {
        return this.dataStore[--this.top];
    }

    function clear() {
        this.top = 0;
    }

    function length() {
        return this.top;
    }



    /* 数制转换函数 */
    function mulBase(num, base) {
        var s = new Stack();
        do {
            s.push(num%base);
            num = Math.floor(num /= base);
        } while(num > 0);
        var converted = "";
        while(s.length() > 0) {
            converted += s.pop();
        }
        return converted;
    }

    alert(mulBase(10, 2));
    

</script>
posted @ 2015-11-26 19:55  钟山  阅读(193)  评论(0编辑  收藏  举报