【问题标题】:Recursive method with return带返回的递归方法
【发布时间】:2016-08-03 14:38:01
【问题描述】:

我必须编写一个递归方法,该方法将计算所有偶数的总和,这些偶数不能与7 以间隔形式1 划分,直到一个参数。

我不能使用任何循环。这是我走了多远,但似乎我的说法不正确。

有什么建议吗?

public static int specialSum (int x){
    return (x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + 1 : 0;
}

public static void main(String[] args) {
    System.out.println(specialSum(16));
}

【问题讨论】:

  • 在哪些方面“不正确”?
  • 你是在数数还是求和?
  • 如果是数字 16,我的结果是 31。(应该是这样的:16 + 12 + 10 + 8 + 6 + 4 + 2,他应该跳过 14,因为它可以除以7) 为什么是 31?好吧,我认为他得到了前两个数字 16、15,然后他就停止了,所以我的陈述不太好。

标签: java recursion methods sum return


【解决方案1】:

无论是否计算当前数字,都需要递归到下一个数字。

boolean divisibleBy2Not14 = ((x % 2 == 0) && (x % 7 != 0);
return (divisibleBy2Not14 ? x : 0) + (x > 0 ? specialSum(x - 1) : 0);

【讨论】:

    【解决方案2】:

    如果您需要找到这些 (x % 2 == 0 && x % 7 != 0) 正数 (x > 0) 的总和:

    public static int specialSum (int x) {
        return x > 0 ?
                specialSum(x - 1) + (x % 2 == 0 && x % 7 != 0 ? x : 0) :
                0;
    }
    

    【讨论】:

    • 首先,非常感谢!那是我没有做对的事情......所以这意味着我需要,而且我实际上可以做不止一个布尔表达式。
    【解决方案3】:

    你的递归逻辑有两个问题:

    1. 它试图返回 count 而不是有效数字的总和
    2. 并且递归不会到达所有分支,因为它会在到达无效案例时立即终止。

    如果你想要总和,你应该返回 specialSum(x-1)+x 而不是 specialSum(x-1)+1。这是一个可行的示例:

    public static int specialSum (int x){
        if(x == 0) return 0; // ← degenerate case
        return ((x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + x : specialSum(x - 1));
    }
    

    您可以通过将specialSum(x - 1) + x 替换为specialSum(x - 2) + x 来添加一些巧妙的简化,因为您知道如果x 是偶数,x - 1 将是奇数。

    【讨论】:

      【解决方案4】:

      你必须像这样改变 specialsum 方法:

      public static int specialSum (int x){
          if(x == 1)  return 0;
          return ((x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + x   : specialSum(x - 1));
      }
      

      【讨论】:

        【解决方案5】:

        处理它的一个好方法是先把它写出来(没有三元运算符)。然后你可以看看是否可以缩短:

           public static int summer( int n ) {
              if ( n < 2 ) {
                 return 0;
              } else if ( (n % 2) == 0 ) {
                 if ( (n % 7) == 0 ) {
                    return summer( n - 2 ); // n-1 is odd, so skip it
                 }
                 return n + summer( n - 2 ); // n-1 is odd, so skip it
              } else {
                 return summer( n - 1 );
              }
           }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-24
          • 1970-01-01
          • 2011-06-26
          • 2014-11-13
          • 2015-12-13
          • 2018-09-18
          • 2014-02-27
          • 2014-10-27
          相关资源
          最近更新 更多