欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript 利用栈实现10进制转化2进制、8进制、16进制

程序员文章站 2024-03-18 20:46:10
...

1、首先封装一个栈

//封装栈类
function Stack() {
    this.items = []

    //栈的相关操作
    //1、将元素压入栈
    Stack.prototype.push = function (element) {
        this.items.push(element)
    }
    //2、将元素出栈
    Stack.prototype.pop = function () {
        return this.items.pop()
    }
    //3、查看栈顶元素
    Stack.prototype.peek = function () {
        return this.items[this.items.length - 1]
    }
    //4、判断栈是否为空
    Stack.prototype.isEmpty = function () {
        return this.items.length === 0
    }
    //5、回去栈中元素的个数
    Stack.prototype.size = function () {
        return this.items.length
    }
    //6、将栈中元素以字符串的方式返回
    Stack.prototype.toString = function () {
        let resultString = ''
        for (let i = 0 ; i < this.items.length ; i++) {
            resultString += this.items[i] + ' '
        }
        return resultString
    }
}

2、实现转化为二进制和八进制的函数

const stack = new Stack()
function DecToBin(Number) {

    let remainder = 0 //余数
    while(Number > 0) {
        remainder = Number % 2 //取余
        stack.push(remainder) //将余数压入栈
        Number = Math.floor(Number / 2) //将商向下取整
    }

    let binString = ''
    while(!stack.isEmpty()) {
        binString += stack.pop() + '' //将所得结果全部出栈即为所求
    }
    return binString
 }

console.log(DecToBin(100));
//如果想实现转化为8进制 将上面的2换成8即可

结果:

1100100

3、实现转化为16进制的函数

const stack = new Stack()
function DecToHex(Number) {
    let remainder = 0 //余数
    const HH = ['A','B','C','D','E','F']
    while(Number) {
        remainder = Number % 16 //取余
        if ( remainder <= 9) {
            stack.push(remainder) // 余数如果小于10 直接压入栈
        } else { // 余数 >= 10 进行进一步的操作 将对应的字母压入栈
            remainder = remainder - 4
            stack.push(HH[remainder % 6])
        }
        Number = Math.floor(Number / 16)
    }

    let resultString = ''
    while(!stack.isEmpty()) {
        resultString += stack.pop() + '' //将所得结果全部出栈即为所求
    }
    return resultString
}

console.log(DecToHex(1010));

结果

3F2
相关标签: javascript js