运用栈结构实现二进制数转为十进制数(JS代码实现)

栈结构是一种很常见的数据结构,就比如我们常用的将一个十进制数转成二进制数的方法-除2取余法。

我们以100为例子,运算情况如下:

  

结果从下至上写为:

很明显我们需要

1.每次把除以2的余数压入栈。

2.把除以2的结果作为下一次的运算数。

3.重复上面两个步骤直到运算数为0。

4.从栈中弹出0和1,最后得到一个二进制序列即为所求。

算法的实现过程不是特别复杂,就像下面这样:

下面是一个运行实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>栈结构</title>
</head>
<body>
    <script>
        function  Stack(){
            this.items=[];
            //进栈操作
            Stack.prototype.push=function(element){
                this.items.push(element);
            }
            //出栈操作
            Stack.prototype.pop=function(){
                return this.items.pop();
            }
            //查看栈顶元素
            Stack.prototype.peek=function(){
                return this.items[this.items.length-1];
            }
            //查看栈是否为空
            Stack.prototype.isEmpty=function(){
                return this.items.length==0;
            }
            //打印栈
            Stack.prototype.toString=function(){
                var resultString='';
                for(var i=0;i<this.items.length;i++){
                    resultString+=this.items[i]+' ';
                }
                return resultString;
            }
        }

        //函数:将十进制转换成二进制
        function dec2bin(decNumber){
            //1.定义栈对象
            var stack=new Stack();
            //2.循环操作
            while(decNumber>0){
                //2.1获取余数,并放入到栈中
                stack.push(decNumber%2);
                //2.2获取整除后的结果用于下一次运算
                decNumber=Math.floor(decNumber/2);
            }
            //从栈中得出0和1
            var binaryString='';
            while(!stack.isEmpty()){
                binaryString+=stack.pop();
            }
            return binaryString;
        }

        //测试十进制转二进制的函数
        alert(dec2bin(100));
    </script>

</body>
</html>

运行结果如下:

猜你喜欢

转载自www.cnblogs.com/appleple/p/11883176.html