十进制转二进制,十进制转任意进制

  • 实现栈,后进先出(LIFO)

        包括往后面添加(push),返回第一个并删除(pop),返回最后一个(peek),是否为空(isEmpty),大小(size),

清空(clear)

class Stack {
constructor(){
this. item = []
}
push ( data) {
this. item. push( data)
}
pop () {
return this. item. pop()
}
peek () {
return this. item[ this. item. length- 1]
}
isEmpty () {
return this. item. length === 0
}
size () {
return this. item. length
}
clear () {
this. item = []
}
}

  • 利用栈特性,实现十进制转二进制

function divideBy2( num) {
var stack = new Stack();
var rest = ''; //余数
var resStr = ''; //返回值
while( num > 0) {
rest = num % 2;
stack. push( rest);
num = Math. floor( num / 2)
}
while(! stack. isEmpty()) {
resStr += stack. pop()
}
return resStr
}
console. log( divideBy2( 10))
console. log( divideBy2( 1))

  •     在十进制实现二进制的基础上,只需要稍微调整一下就可以实现十进制转二进制了,具体代码如下:

function divideByAny( num, bit) {
var stack = new Stack();
var rest = ''; //余数
var resStr = ''; //返回值
var str = '0123456789ABCDEF'
while( num > 0) {
rest = num % bit;
stack. push( rest);
num = Math. floor( num / bit);
}
while(! stack. isEmpty()) {
resStr += str[ stack. pop()];
}
return resStr;
}
console. log( divideByAny( 10, 16))
console. log( divideByAny( 2, 16))
console. log( divideByAny( 20, 16))

猜你喜欢

转载自blog.csdn.net/luchuanqi67/article/details/80665544