进制转换可以使用使用取余法来实现
基本上是学习编程最常见的一个练习。
学习几个基本的单词
被除数: dividend
除数: divisor
商: quotient
余数: remainder
function numberConversion(num, base) {
var stack = new Stack();
var base_str = "0123456789ABCDEF";
var quotient = Math.floor(num / base);
var remainder = num % base;
stack.push(remainder);
while (quotient != 0) {
remainder = quotient % base;
quotient = Math.floor(quotient / base);
stack.push(remainder);
}
/*出栈拼接数据*/
var num = stack.pop();
var result = "";
while(num != undefined) {
result += base_str[num];
num = stack.pop();
}
return result;
}
/*不使用栈的结构也可以使用数组逆转来实现*/
function myNumberConversion (num, base) {
var base_str = "0123456789ABCDEF";
var quotient = Math.floor(num / base);
var remainder = num % base;
var result = [];
result.push(remainder);
while(quotient != 0) {
remainder = quotient % base;
quotient = Math.floor(quotient / base);
result.push(remainder);
}
return result.reverse().join("");
}