简体   繁体   中英

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:

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. 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. 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. So we can just call the same function on n-3.

    else
        return isDivide(n-3);
}

And you're done!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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