-
-
Save WunGCQ/057eb7d3189ebf80808bc1e2f87cfe29 to your computer and use it in GitHub Desktop.
实现一个小的进制转换器...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function log(a,b){ | |
return Math.log(b)/Math.log(a); | |
} | |
function convert(_input, source, target) { | |
var input = _input.toString(); | |
var I_L = source.length,T_L = target.length; | |
var len = input.length; | |
var num = input.split('').reduce((res,letter,i)=>{ | |
var index = source.indexOf(letter); | |
var temp = index * Math.pow(I_L,len - i -1); | |
//console.log(`${temp} = ${index} * (${I_L} ^ ${len -i - 1})`); | |
res += temp; | |
return res; | |
},0); | |
if(num == 0){ | |
return target[0]; | |
} | |
var lex = Math.floor(log(T_L,num))+1; | |
var _num = num; | |
// console.log(`${input} -> ${num}`); | |
var res = ""; | |
while( lex > 0 ){ | |
var Y = Math.pow(T_L,lex-1); | |
var temp = Math.floor(_num / Y); | |
_num -= Y*temp; | |
res += target[temp]; | |
lex--; | |
} | |
console.log(res); | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment