[C++/JavaScript]数据结构:栈和数列>案例引入(数制的转换)

1 案例1:数制的转换

1.1 背景与原理

1.2 编程复现

(JavaScript版 复现)

function convert(value, d){
    stack = []; // 栈
    result = []; // 一般线性表 or 队列
	while(value!=0){
        mod = value%d;
		value = Math.floor(value/d); // 整除 (向下取整)
		stack.push(mod);
    }
	while(stack.length!=0){
		result.push(stack.pop());
	}
	return result;
}

测试运行:

convert(1098, 2); // 正确答案应为: 1000 100 10 10

输出:

[1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0]

2 参考资料

1 《数据结构(C语言版 第二版)》.严蔚敏.李冬梅.吴伟民

原文地址:https://www.cnblogs.com/johnnyzen/p/11406270.html