如何使我的函数变成递归函数?(Java)

huangapple go评论67阅读模式
英文:

How to get my function to be recursive? (Java)

问题

我正在编写一个递归函数,它将接收一个存有 "int" 元素的栈,并输出栈中元素平方和的结果。以下是我的代码:

public int sum_sqr_rec(Stack<Integer> stk) {
    int sum = 0;
    for (int i = 0; i < stk.size(); i++) {
        sum += (stk.get(i) * stk.get(i));
    }
    return sum;
}
英文:

I'm having to make a recursive function that will receive a stack of "int" and output the sum of the squares of the elements in the stack.
Here is what I have

public int sum_sqr_rec(Stack&lt;Integer&gt; stk){
int sum = 0;
for (int i=0; i&lt;stk.size(); i++){
sum += (stk.get(i) * stk.get(i));
}
return sum;
}

答案1

得分: 1

以下是翻译好的内容:

递归函数中最重要的是确定何时终止它。

第二个需要考虑的重要因素是在终止递归时返回什么。当你开始累加数字时,你可以从 sum = 0 开始。对于一个用于计算数字和的递归函数,在终止时可以返回相同的值(即 0)。同样地,对于一个用于计算数字乘积的递归函数,在终止时可以返回 1

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        stack.add(2);
        stack.add(3);
        stack.add(4);
        stack.add(5);
        System.out.println(sum_sqr_rec(stack));
    }

    static int sum_sqr_rec(Stack<Integer> stk) {
        if (stk.isEmpty()) {
            return 0;
        }
        int n = stk.pop();
        return n * n + sum_sqr_rec(stk);
    }
}

输出:

54
英文:

The most important thing you need to determine for a recursive function is when to terminate it.

The second important thing to consider is what to return when you terminate it. When you start adding numbers, you start with sum = 0. From a recursive function, which is supposed to calculate the sum of numbers, the same value (i.e. 0) can be returned when you terminate it. Similarly, from a recursive function, which is supposed to return the product of numbers, you can return 1 on termination.

import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;();
		stack.add(2);
		stack.add(3);
		stack.add(4);
		stack.add(5);
		System.out.println(sum_sqr_rec(stack));
	}

	static int sum_sqr_rec(Stack&lt;Integer&gt; stk) {
		if (stk.isEmpty()) {
			return 0;
		}
		int n = stk.pop();
		return n * n + sum_sqr_rec(stk);
	}
}

Output:

54

答案2

得分: 0

你可以像这样使用递归:

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.add(2);
        stack.add(2);
        stack.add(4);
        stack.add(5);
        System.out.println(sum_sqr_rec(stack));
    }

    public static int sum_sqr_rec(Stack<Integer> stack) {
        if (stack.isEmpty())
            return 0;
        return stack.peek() * stack.pop() + sum_sqr_rec(stack);
    }
英文:

You can use recursion like this:

    public static void main(String[] args) {
        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();
        stack.add(2);
        stack.add(2);
        stack.add(4);
        stack.add(5);
        System.out.println(sum_sqr_rec(stack));
    }

    public static int sum_sqr_rec(Stack&lt;Integer&gt; stack) {
        if (stack.isEmpty())
            return 0;
        return stack.peek() * stack.pop() + sum_sqr_rec(stack);
    }

答案3

得分: 0

注意,我使用的是Deque接口,而不是直接使用Stack类(文档建议优先使用Deque接口)。

public int recursive(Deque<Integer> stk){
    if (stk.isEmpty()){
        return 0;
    }
    return (int) Math.pow(stk.pop(), 2) + recursive(stk);
}
英文:

Note that I use Deque interface rather than Stack class directly (documentation says it should be used in preference to the Stack class).

    public int recursive(Deque&lt;Integer&gt; stk){
        if (stk.Empty()){
            return 0;
        }
        return Math.pow(stack.pop(), 2) + recursive(stk);
    }


</details>



# 答案4
**得分**: 0

有很多种方法可以做到这一点。但是,如果您不想销毁堆栈,可以按照以下方式进行。堆栈在返回过程中恢复。

- `n` 被弹出。这使数字堆栈减少,并将 `n` 保留在本地调用堆栈中以供以后使用。
- 元素的平方保存在 `k` 中的方法调用堆栈中。

- `r` 被初始化为最终总数。
- 一旦堆栈为空,只需将 `n` 重新推回 `stk` 并返回保存的平方和。
```java
static int sum_sqr_rec(Stack<Integer> stk) {
      int n = stk.pop();
	  int k = n*n;
	  int r = 0;
	  if (!stk.isEmpty()) {
			r = sum_sqr_rec(stk);
	  }
	  stk.push(n);
	  return r + k;
}

使用以下语句的调用序列。

System.out.println(stack);
System.out.println(sum_sqr_rec(stack));
System.out.println(stack);

结果如下

[2, 3, 4, 5]
54
[2, 3, 4, 5]
英文:

Lots of ways to do this. But if you don't want to destroy the stack you can do it this way. The stack is restored during the return process.

  • n is popped. This depletes the stack of numbers and keeps n in the local call stack for later use.

  • The square of the element is saved on the call stack of the method in k

  • r is initialized for the final tally.

  • Once the stack is empty, simply push n back on stk and return the sums of the saved squares.

static int sum_sqr_rec(Stack&lt;Integer&gt; stk) {
      int n = stk.pop();
	  int k = n*n;
	  int r = 0;
	  if (!stk.isEmpty()) {
			r = sum_sqr_rec(stk);
	  }
	  stk.push(n);
	  return r + k;
}

Using this call sequence of statements.

System.out.println(stack);
System.out.println(sum_sqr_rec(stack));
System.out.println(stack);

Results in the following

[2, 3, 4, 5]
54
[2, 3, 4, 5]

</details>



huangapple
  • 本文由 发表于 2020年5月4日 05:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/61581977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定