简体   繁体   English

用于检查整数是否可整除的递归布尔方法

[英]Recursive Boolean method to check if integer is divisible

This is what i have so far, it works, but its not recursive. 到目前为止,这就是我所能实现的,但是它不是递归的。 Any idea how to translate this into recursion 任何想法如何将其转换为递归

   public static boolean isDivide(int n)
   {
   if (n < 10) System.out.println (n);
   int sum = 0;
   while (n > 0)
   {
   sum += n % 10;
   n = n / 10;
   }
   while (sum >= 0)
   {
   sum -=3;
   }
   //System.out.println(n==0);
   return n==0;

   } 
public static boolean isDivisibleBy3(int n)
{
    if(n == 0) return true;
    if(n < 0) return false;
    return isDivisibleBy3(n - 3);
} 

for n >= 0. If you need to check negative numbers: n> =0。如果需要检查负数:

public static boolean isDivisibleBy3(int n) {
    if(n == 0) return true; 
    if(n == -1 || n == -2 || n == 1 || n == 2) return false; 
    if (n < 0) return isDivisibleBy3(n + 3); 
    else return isDivisibleBy3(n - 3); 
}

It's pretty easy to replace while loops with tail end recursions. 用尾端递归替换while循环非常容易。 For recursion, you need two things: a general case, and a base case. 对于递归,您需要两件事:一个普通情况和一个基本情况。 The base case is usually easier, so it's best to start with that. 基本情况通常比较容易,所以最好从此开始。 What's the simplest possible input this program can get? 这个程序可以得到的最简单的输入是什么? It's 0-3. 是0-3。 So here's the base case: 所以这是基本情况:

public static boolean isDivide(int n)
{
    if(n==0||n==3)
        return true;
    else if(n==1||n==2)
        return false;

For this, the general case is also pretty easy. 为此,一般情况也很容易。 For any n that is divisible by 3, so is n-3. 对于任何可被3整除的n,n-3也是如此。 So we can just call the same function on n-3. 因此,我们可以在n-3上调用相同的函数。

    else
        return isDivide(n-3);
}

And you're done! 大功告成!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM