Recursive function to check digits

2020-05-01 09:47发布

问题:

Write a recursive function to check how many digits in the number can be divided by the digit which is after them. Example: 84963 should return 2, because 8 can be divided by 4 and 6 can be divided by 3. My function doesnt seem to output anything at all.

#include <iostream>

using namespace std;

int fun (int n);

int main()
{
    int n;
    cin >> n;
    cout << fun(n) << endl;
    return 0;
}

int fun(int n){
    int count = 0;
    if (fun(n % 100) % fun(n % 10) == 0)
        count++;
    return count;
}

回答1:

Your recursion does not make much sense at the moment. A more logical approach to this would be to see if the last number (so 1 in 321), can currently divide the second last number (so 2 in 321). You could do this by defining a function that checks if that is possible, and recursively passes on the number divided by 10. That function would look something like this:

int fun(int n)
{
  if (n < 10)
    return 0;
  int last = n % 10;
  n = n / 10;
  int secondlast = n % 10;
  if (secondlast != 0 && last != 0 && secondlast % last == 0) 
    return 1 + fun(n);
  else
    return fun(n);
}

Update note: After looking into Vlad from moscow's comment, I moved the last != 0 part of the condition forward, to solve a bug (divide by 0).

The problem Vlad from moscow was talking about is the following: If you want, for example, the part 04 to count as 0, you should use the code as it is above. Otherwise you should remove the secondlast != 0 part.



回答2:

int countIfDiv(int num) {
    int pair = num % 100;
    int first = pair / 10;
    if (first == 0) return 0;
    int second = pair % 10;
    int next = num / 10;
    return first % second == 0 ? 1 + countIfDiv(next) : 0 + countIfDiv(next);
}

Just pull a pair, try the division, then chop the last number and repeat.



回答3:

You're not actually updating n value so you get into an infinite loop, on the other hand, your function is, initially, only designed for 3 digits number. I think that it should be something similar to:

int fun(int n, int ant, int count){
    if( n == 0 )
        return count;

    if (ant != 0 &&
             (n%10) % ant == 0)
        count++;

    return fun(n/10, n%10, count);
}

I should work with different number of digits.



回答4:

The valid code will be

size_t fun( int n )
{
    const int base = 10;
    int digit = n % base;
    n /= base;

    return ( n == 0 ? 
             0      : 
             ( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}