用栈的特性将二进制转化为十进制

利用栈的特性将二进制转化为十进制
10001000     ->      136

0 * 2^{0} + 0 * 2^{1} +0 * 2^{2} +{\color{Red} 1 * 2^{3}} +0 * 2^{4} +0 * 2^{5} +0 * 2^{6} +{\color{Red} 1 * 2^{7}} = {\color{Red} 136}

 如上公式,可将二进制入栈。然后一次出栈,将其值进行处理,求和。即得到十进制值。

下边是自己实现的栈以及将二进制转化为十进制的代码

public class Stack {
    //最大容量
    private int maxSize;
    //栈顶指针
    private int top;
    //栈底指针
    private int base;
    //存放元素
    private int[] arr;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        top = base = 0;
    }

    /**
     * 入栈,栈满返回false
     * @param value
     * @return
     */
    public boolean push(int value) {
        if (top - base >= maxSize) {
            return false;
        }
        arr[top++] = value;
        return true;
    }

    /**
     * 出栈
     * @return
     */
    public int pop() {
        if (top == base) {
            return -1;
        }
        return arr[--top];
    }

    /**
     * 查看栈顶元素
     * @return
     */
    public int peek() {
        if (top == base) {
            return -1;
        }
        return arr[top - 1];
    }

    /**
     * 判断栈满
     * @return
     */
    public boolean isFull() {
        return top == maxSize;
    }

    /**
     * 判断栈空
     * @return
     */
    public boolean isEmpty() {
        return top == base;
    }
}

 

package com.yc.algorithm.stack;

/**
 * 利用栈的特性将二进制转化为十进制
 * 10001000     ->      136
 * @author yc
 */
public class twoTOTen {
    public static void main(String[] args) {
        Stack stack = new Stack(8);
        stack.push(1);
        stack.push(0);
        stack.push(0);
        stack.push(0);

        stack.push(1);
        stack.push(0);
        stack.push(0);
        stack.push(0);

        int i = 0;
        int sum = 0;
        while (!stack.isEmpty()) {
            int temp = stack.pop();
            temp *= (int)Math.pow(2, i++);
            sum += temp;
        }
        System.out.println(sum);
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值