通过栈来实现进制转换
function mulBase(num,base){
var sta=new Stack()
do{
sta.push(num%base)
num=Math.floor(num/=base)
}
while(num>0)
var converted=""
while(sta.length()>0){
converted+=sta.pop()
}
return converted
}
console.log(mulBase(9,2))
算法如下:
第一步:将num取余base的值入栈
第二步,将num的值变成num/base的整数部分
第三步:重复第一步和第二步,直到num=0
第四步:将栈内元素逐个出栈,用一个空字符串将其加起来,由于栈的特点是后进先出(LIFO),所以这时我们就得到了转换后的数值(如果想拿到数值,可以通过(parseInt(converted))来获得
这个方法只能用来转换base在2-9的情况
下面我们来回顾一下栈
定义栈的构造方法
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 pop(){
return this.dataStore[--this.top]
}
function peek(){
return this.dataStore[this.top-1]
}
function length(){
return this.top
}
function clear(){
this.top=0
}
实例化
var sta=new Stack()