进制转换(基数为2~9)适合用栈(stack)这种数据结构来实现。
Stack类的定义
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 clear() {
this.top = 0;
}
function length() {
return this.top
}
//进制转换实现
function mulBase(num, base) {
let s = new Stack();
while(num > 0) {
s.push(num%base);
num = Math.floor(num/base)
}
let coverted = '';
while(s.length() > 0) {
coverted +=s.pop()
}
return coverted
}