算法,十进制数转任意进制数

直接法把十进制转八进制或者十六进制,按照除8或者16取余,直到商为0为止。

 

 下面用JavaScript实现一下

var Stack = (function () {
    var items = new WeakMap();
    //先入后出,后入先出
    class Stack {
        constructor() {
            items.set(this, []);
        }
        push(ele) {
            //入栈
            var ls = items.get(this);
            ls.push(ele);
        }
        pop() {
            //出栈
            var ls = items.get(this);
            return ls.pop();
        }
        size() {
            //获取栈的长度
            var ls = items.get(this);
            return ls.length;
        }
        print() {
            //打印栈
            var ls = items.get(this);
            return ls.toString();
        }
    }
    return Stack;
})();

/**
 * num 需要转化的数字
 * base 转化的进制,默认为 2
 * */
function devide(num, base) {
    base = Math.floor(base) || 2;
    if (typeof num != "number" || num < 0 || base > 36 || base < 2) {
        throw new Error("参数错误");
        return '';
    }
    num = Math.floor(num);

    var code = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var stack = new Stack();
    var res = '';
    var rem;
    while (num > 0) {
        rem = num % base;
        stack.push(rem);
        num = Math.floor(num / base);
    }

    while (stack.size() > 0) {
        res += code[stack.pop()];
    }

    return res;
}
console.log(devide(35, 36))

任意进制转十进制

function transfrom(num,base){
    //任意进制转十进制
    var bases = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];
    var config = {};
    for(var k = 0; k < base; k++){
        config[bases[k]] = k;
    }
    num = String(num);
    num = num.toUpperCase();
    var count =  0;
    var res = 0;
    var i;
    while(num.length > 0){
        i  = num[num.length - 1];
        i = config[i];
        res = res + i * Math.pow(base,count);
        num = num.substr(0,num.length-1);
        count++;
    }
    return res;
}
 
console.log(transfrom('ff',16));
console.log(transfrom('11',2));

 

posted @ 2020-05-19 23:48  Magi黄元  阅读(678)  评论(0编辑  收藏  举报