【问题标题】:Recursive method to find the number of appereances in a number递归方法查找数字中出现的次数
【发布时间】:2020-04-30 15:00:12
【问题描述】:
public static boolean countExactly(int num, int digit, int count) {
    if(digit <= 9) {
        return false;
    }
    if(num % 10 == digit) {
        countExactly(num % 10 + num / 10, digit, count++);
    }
    return true;
}

我的代码有什么问题??? 我正在尝试编写一种递归方法来查找数字中出现的次数。 编写一个递归函数,从另一个整数编码一个正整数 num,西班牙数字 没有负数。如果数字恰好出现在数字 number 上,该函数返回 true 计算次数,否则返回false。

示例:输入:122231 位:2 计数:3 输出:真

【问题讨论】:

  • 你的问题到底是什么?
  • 在这个输入上我得到错误
  • @davidkokiashvili - 如果其中一个答案解决了您的问题,您可以通过将其标记为已接受来帮助社区。接受的答案有助于未来的访问者自信地使用该解决方案。查看meta.stackexchange.com/questions/5234/… 了解如何操作。

标签: java recursion


【解决方案1】:

以下是您的方法存在的问题:

  1. 您在递归调用中传递count++,它将始终作为count 传递,然后该值将递增,即永远不会使用递增的值。它应该是++count--count,具体取决于您的逻辑。
  2. 您正在调用 countExactly(num % 10 + num / 10, digit, count++),这就像调用 void 函数/方法。它在语法上是正确的,但在您的程序中没有任何用途?

你应该这样做:

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(countExactly(122231, 2, 3));
        System.out.println(countExactly(122231, 2, 2));
        System.out.println(countExactly(122231, 2, 4));
        System.out.println(countExactly(1222231, 2, 4));
        System.out.println(countExactly(2222231, 2, 4));
        System.out.println(countExactly(2222231, 2, 5));
        System.out.println(countExactly(2222231, 2, 3));
    }

    static boolean countExactly(int num, int digit, int count) {
        if ((num == digit && count == 1) || (num != digit && num <= 9 && count == 0)) {
            return true;
        }
        if (num <= 9) {
            return false;
        }
        if (num % 10 == digit) {
            return countExactly(num / 10, digit, --count);
        } else {
            return countExactly(num / 10, digit, count);
        }
    }
}

输出:

true
false
false
true
false
true
false

【讨论】:

    【解决方案2】:

    你可以试试这个

    public static boolean countExactly(int num, int digit, int count) {
        if (num <= 9 ) {
            return (digit==num && count==1) || (digit!=num && count==0) ;
        }
        if (num % 10 == digit) {
            count--;
        }
        return countExactly( num / 10, digit, count);
    }
    

    尝试输入值

    • 2、2、1
    • 122231 , 2, 3
    • 12231 , 2, 2
    • 1、2、0

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 1970-01-01
      • 2019-02-28
      • 2020-01-15
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多