编辑代码

/**
 一、首先需要知道进制转换是怎么做的,我们先来举个例子,10转为2进制怎么表示

 10/2 = 5  余数:0 
  5/2 = 2  余数:1
  2/2 = 1  余数:0
  1/2 = 0  余数:1

  我们把余数按栈(先进后出)存放。开始存放的是0101,先从栈顶依次取出1010
  所以10用二进制表示为 1010

 二、思路
 1、利用栈先进后出
 2、递归

 
 */

// 进制转换
// function decimalTrans(num,decimal = 2){
//     let arr = [];
//     let rem ;//取余
//     let str = '0123456789abcdefghijklmnopqrstuvwxyz';
//     while(num > 0){
//         rem = num % decimal
//         num = Math.floor(num /decimal);
//         arr.unshift(str.charAt(rem));
//     }
//     return arr.join('');
// }

// 栈:时间复杂度O(2n) 
function decimalTrans(num,decimal = 2){
    let arr = [];
    let rem ;//取余
    let str = '0123456789abcdefghijklmnopqrstuvwxyz';

    while(num > 0){
        rem = num % decimal
        num = Math.floor(num /decimal);
        arr.push(str.charAt(rem));
    }
    let res='';
    while(arr.length){
        res+=arr.pop();
    }
    return res;
}


//递归
function decimalTrans(num,decimal = 2,){
    let rem ;//取余
    let str = '0123456789abcdefghijklmnopqrstuvwxyz';
    if(num <= 0){
        return '';
    }else{
        rem = num % decimal;
        num = Math.floor(num /decimal);
        return decimalTrans(num,decimal) + str.charAt(rem);
    } 
}




let num = 10001;
console.log(num.toString(2))
console.log(decimalTrans(num));

console.log(num.toString(16))
console.log(decimalTrans(num,16));

console.log(num.toString(32))
console.log(decimalTrans(num,32));