乘以pop'd整数

问题描述 投票:0回答:2

我正在写一段代码从Stack中弹出并繁殖。我知道我可以打印我的pop'd整数,但是如果我弹出另一个整数,我如何跟踪一个pop'd整数?

我正在尝试使用基本计数器编写一个for循环来弹出顶部整数,将其保存到变量,然后将该变量乘以下一个弹出的整数。

static LStack<Integer> stack = new LStack<Integer>();


        static public void main (String[] args) 
        { 


        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        for(int i = stack.length(); i <= 0; i++) {
            stack.pop();


        }

        }
java stack tail-recursion
2个回答
0
投票

您可能会发现使用while循环更容易/更清楚:

int result = stack.pop();
while (!stack.empty()) {
    result *= stack.pop();
}

如果你必须使用for循环:

int result;
for (result = stack.pop(); !stack.empty();)
    result *= stack.pop();
}

无论如何,关键是用堆栈顶部的值初始化最终结果,然后将它乘以从堆栈弹出的每个元素。


0
投票
static LStack<Integer> stack = new LStack<Integer>();

/ * fact()函数* /

    public static void main(String[] args) {
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);




      System.out.println(calc(stack.pop()));
    }

    public static long calc(long n) {
        if (n <= 1)
            return 1;
        else
            return n * calc(n - 1);

}

    }

这是我最终使用的,从另一个帖子实现计算器,它似乎工作,并允许我推动额外的整数。谢谢大家的时间!

© www.soinside.com 2019 - 2024. All rights reserved.