java - 递归 - 在二进制表示中查找 1 的连续计数

标签 java algorithm recursion data-structures binary

我开始学习递归并尝试解决以下问题: 问题陈述: 需要查找二进制数中连续的个数:

Example:

The binary representation of 13 is 1011 , so the maximum number of consecutive 1's is 2.

我在 while 循环的帮助下实现了上述目标。然而,我试图通过递归实现解决方案但面临问题:

使用 While 循环:

int counter = 0, max =0, n=13;
    while (n > 0) {
        int rem = n%2;
        if (rem==1) counter++; 
        else counter=0;
        max = Math.max(counter, max);
        n/=2;
    }
    System.out.println(max);

Result : 2

递归:

public static int returnCount(int n,int count,int max){

        if (n > 0){
            int temp=n%2;
            if(temp==1)
                count++;
            else
                count=0;

            n/=2;
            max=Math.max(count,max);
            returnCount(n,count,max);           
        }
        return max;
    }

结果:1​​

请帮我纠正上面代码段中的错误。

最佳答案

当您对 returnCount 进行递归调用时,您永远不会使用它返回的值。在您的解决方案中,如果 n 为奇数,则 returnCount 始终返回 1,因为从未使用对 returnCount 的递归调用的返回值。

public static int returnCount(int n, int count, int max) {
    if (n > 0){
        if(n % 2 == 1)
            count++;
        else
            count = 0;
        n /= 2;
        max = Math.max(count, max);
        max = returnCount(n, count, max);           
    }
    return max;
}

为了证明我的观点,我将稍微跟踪一下代码。如果我们对您的代码运行以下调用:

int answer = returnCount(13, 0, 0);

我们最终调用了以下方法:

  1. returnCount(13, 0, 0)
  2. returnCount(6, 1, 1)
  3. returnCount(3, 0, 1)
  4. returnCount(1, 1, 1)
  5. returnCount(0, 2, 2)

在第四次调用的迭代过程中,count 递增到 2,max 被赋值为 2,因为 count> 最大。到第五次调用时,找到了答案,max 仍然是 2。

但是,当从第一次调用返回时,局部变量 max 仍被赋值 1。我们问题的正确答案丢失了,因为它从未从您的第四次和第五次调用中返回解决方案。

关于java - 递归 - 在二进制表示中查找 1 的连续计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901342/

相关文章:

java - Java错误-错误的源文件:文件不包含类x。请删除或确保它出现

algorithm - 将一个词转换为另一个词的最短路径

algorithm - 查询n次时如何改进Dijkstra算法?

arrays - 找到最少的转换次数

algorithm - 以最大增益顺序跳跃 - 动态规划

java - Esper窗口使用: Recalculation based on event leaving window

java - E*Trade OAuth API (Java) 存在问题

java - 如何在 Java 中的 JSON 字符串中在不知道确切键的情况下屏蔽特定值

python - 递归线性搜索 - 返回列表索引

javascript - 理解列表的递归