【问题标题】:count number of digit using recursive method使用递归方法计算位数
【发布时间】:2016-03-22 13:30:59
【问题描述】:

给定一个非负整数 n,递归地计算(无循环) 8 作为数字出现的计数,除了紧靠其左侧的另一个 8 的 8 计数加倍,所以8818 产生 4。请注意,mod (%) 除以 10 产生最右边的数字(126 % 10 是 6),而除以 (/) 除以 10 会删除最右边的数字(126 / 10 是 12)。

count8(8) → 1
count8(818) → 2
count8(8818) → 4

我的程序似乎无法计算双 '8'。这是代码。

public int count8(int n) {
    boolean flag = false;
    if(n<10)
    {
      if (n==8)
      {
         if(flag == true)
             return 2;
         else 
         { 
             flag = true;
             return 1;
         }
      }
      else 
      {
        flag = false;
        return 0;
      }
    }

    else
       return count8(n%10)+count8(n/10);

}

我想知道最后一行是否出错,但我不知道如何检查。期待您的帮助。谢谢!

【问题讨论】:

  • 8888 的答案是什么? 3 *4 = 12?
  • 如果我理解正确的话,应该是7
  • 这可能会有所帮助。 stackoverflow.com/questions/275944/…
  • 这看起来像是一道作业题。你不这么认为,在堆栈上询问有点重要。问问同学,试试看。有很多方法可以解决它,但最明显的一个提示是:添加一个布尔参数
  • 你介绍的这个标志也应该是不必要的。

标签: java recursion


【解决方案1】:

状态(是前一个数字)传递给方法:

private static int count8(int n, boolean eight) {
  if (n <= 0)
    return 0;
  else if (n % 10 == 8)
    return 1 + (eight ? 1 : 0) + count8(n / 10, true);
  else
    return count8(n / 10, false);
}

public static int count8(int n) {
  return count8(n, false);
}

【讨论】:

  • 正确,但这显然是一道作业题。我认为你应该让他自己尝试解决。
  • 谢谢你们!我知道我现在的问题在哪里。顺便说一句,这不是我的作业。我正在自学,这是codingBat的问题。非常感谢!
  • 如果 n = 88 则失败,返回 3
  • @Zeus:这似乎是正确的“左边的 8 是双倍的”所以我们有 1 + 2 == 3;请查看8818 示例,该示例返回4
【解决方案2】:

您的标志变量只是本地的。你只有一次读过它:if (flag == true),因为在此之前你从未改变它的值,所以它总是错误的。

您使这比它必须要复杂得多。根本不需要额外的参数。

public int count8(int n)
{
    if (n % 100 == 88) return count8(n/10) + 2;
    if (n % 10 == 8) return count8(n/10) + 1;
    if (n < 10) return 0;
    return count8(n/10);
}

【讨论】:

  • 感谢您的回答!我知道问题出在哪里。
【解决方案3】:

你可以这样试试:

public int count8(int n) {
    if (n < 10)
        return n == 8: 1 ? 0;

    int count = 0;
    String num = Integer.toString(n);
    int numLength = num.length();

    if (numLength % 2 != 0)
        num += "0";

    if ((num.charAt(numLength / 2) == num.charAt(numLength / 2 - 1)) && (num.charAt(numLength / 2) == "8"))
        count++;

    String left = num.substring(0, numLength / 2);
    int leftInt = Integer.parseInt(left);
    String rigth = num.substring(numLength / 2);
    int rigthInt = Integer.parseInt(rigth);

    return count + count8(leftInt) + count8(rigthInt);
}

【讨论】:

  • 这是一个纯粹的算术问题,所以转换为String(即String num = Integer.toString(n))看起来很难看。
  • 它可以是一种解决方案,比算术更具算法性。为什么不呢?
【解决方案4】:

C++

int count8(int n) {
    return n == 0 ? 0 : (n % 10 == 8) + (n % 100 == 88) + count8(n/10);
}

Java 和 C#

int count8(int n) {
    if (n==0) return 0;
    if(n % 100 == 88)
        return 2 + count8(n / 10);
    if(n % 10 == 8)
        return 1 + count8(n / 10);

    return count8(n / 10);
}

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多