JS使用栈实现十进制转二进制

最近在准备面试,复习到了数据结构与算法的知识,到了这块内容,的特点大家都知道,先进后出

数据结构的特点决定了它的应用。

大家在准备面试的时候,多多少少都会复习到数据结构的知识,大部分人都觉得这种东西没用,在日常的开发基本用不到,就是为了面试造火箭,啥啥啥的。

数据结构一定不是无用的,无论是前端还是后端数据都是我们最关注的点。

其实前端的任务,我们可以简单总结为,收集数据展示数据
后端的任务,我们可以总结为,处理数据存储数据

无论你在开发什么应用,都不可能离开数据,那么问题就来了,数据不是凭空来,凭空去的,它需要东西来存储的,这就有了数据结构。

大家为什么会觉得学习数据结构没有用,因为在大部分的场景下,我们都用不到很多种类的数据结构,一直在重复使用像数组这种简单易操作的数据结构。但是,不适用或者很少使用不代表它不存在。

今天给大家介绍一下使用这种数据结构实现十进制转二进制

直接贴代码:

class Stack {
    
    
    constructor() {
    
    
        this.count = 0;
        this.items = {
    
    };
    }
    push(element) {
    
    
        this.items[this.count] = element;
        this.count ++;
    }
    size() {
    
    
        return this.count;
    }
    isEmpty() {
    
    
        return this.count === 0;
    }
    pop() {
    
    
        if(this.isEmpty()) {
    
    
            return undefined;
        }
        this.count--;
        const result = this.items[this.count];
        delete this.items[this.count];
        return result;
    }
    peek() {
    
    
        if(this.isEmpty()) {
    
    
            return undefined;
        }
        return this.items[this.count-1];
    }
    clear() {
    
    
        this.items = {
    
    };
        this.count = 0;
    }
    toString() {
    
    
        if(this.isEmpty()) {
    
    
            return '';
        }
        let objString = `${
      
      this.items[0]}`;
        for(let i = 1; i < this.count; i++) {
    
    
            objString = `${
      
      objString},${
      
      this.items[i]}`;
        }
        return objString;
    }
}

function decimalToBinary(decNumber) {
    
    
    const remStack = new Stack();
    let number = decNumber;
    let rem;
    let binaryString = '';

    while(number > 0) {
    
    
        rem = Math.floor(number % 2);
        
        remStack.push(rem);
        number = Math.floor(number / 2);
    }

    while(!remStack.isEmpty()) {
    
    
        binaryString += remStack.pop().toString();
    }
    return binaryString;
}

console.log(decimalToBinary(20))

大概解释一下代码结构。

首先我们定义了一个类,写了一些常用的属性方法,完成一个基本的结构。decimalToBinary这个函数就是用来封装十进制转二进制的操作。

实现的思路大概就是,当除法不为0时,我们会获得一个余数,放到栈里,然后让结果继续除以2。最后,用pop方法把栈中的元素都移除,把出栈的元素连接成字符串。

有任何问题都可以联系我。
QQ:505417246
微信:18331092918
微信公众号:Code程序人生
个人博客:https://Creator12333.github.io(详细总结一些面试题,以及前端进阶的内容,CSDN写偏基础的内容)

猜你喜欢

转载自blog.csdn.net/m0_46171043/article/details/117753453