Home > Software engineering >  Returns the length of the longest sequence of identical digits found in num recursive
Returns the length of the longest sequence of identical digits found in num recursive

Time:12-12

I had an assignement;

"Write a recursive static method that accepts a positive integer num and returns the length of the longest sequence of identical digits found in num."

This is the solution I did

public static int equalDigits (int num)
{
    return equalDigits(num,1,0);
}

private static int equalDigits (int num, int count, int max){ 
    if (num < 10)
        return 1;
    if (num/10 == num)
        count  ;
    else
        count = 1;
    max = count > max ? count : max;
    return Math.max(max,equalDigits(num/10,count,max));
}

But my lecturer said it can be done without using helper method. I can't figured how exactly it's possible.

CodePudding user response:

Here is some code using your methodology, so without using String (which I would consider ugly):

public static int equalDigits(int num)
{
    // this is a so-called guard statement at the start to disallow invalid arguments
    if (num < 0) {
        throw new IllegalArgumentException("Expecting positive value or zero");
    }
    
    int currentDigit = -1; // "magic value" outside of range
    int count = 0;
    int maxCount = 0;
    int x = num; // good practice not to operate on parameters
    while (x > 0) {
        int digit = x % 10;
        if (digit == currentDigit) {
            count  ;
        } else {
            // only update max count when needed
            // TODO set maxcount
            // TODO something with digits

            // don't forget the initial digit, so not zero
            // TODO set initial count
        }
        x /= 10; // yes, it exists, is identical to x = x / 10
    }
    // if the last count was higher we still need to adjust
    // TODO set maxcount
    
    return maxCount;
}

I've removed the stuff that you need to get it to work, but I've shown how you can do this without recursive operations, as that can be hard to refactor.

CodePudding user response:

This solution is by no means efficient, and it makes way more recursive calls than your solution, but it works with a single argument.

public static int longestSequence(int num) {
  if (num < 10) {
    return 0;
  }

  int lastDigit = num % 10;
  int rest = num / 10;

  int count = longestSequence(rest);

  if (lastDigit == (rest % 10)) {
    count  ;
  } else {
    count = 1;
  }

  return Math.max(count, longestSequence(rest));
}
  • Related