1

Write a static method called digitsInARow that takes an integer n as a parameter and that returns the highest number of digits that appear in a row in the base-10 representation of n. For many numbers the answer will be 1 because they don't have adjacent digits that match. But for a number like 3555585, the answer is 4 because there are four occurrences of the digit 5 that appear in a row. You are NOT allowed to use a String to solve this problem. You may assume that the value passed to the method is greater than or equal to 0.

public static int digitsInARow(int n) {
    if (n / 10 == 0) {
        return 1;
    }
    int count = 0;
    int count1 = 0;

    while (n > 0) {
        int digit = n % 10;
        int a = n / 10;
        if (digit == a % 10) {
            count++;
        } else {
            count1 = Math.max(count1, count);
            count = 0;
        }        
        n = n / 10;
    }
    return Math.max(count, count1);
}

I know the if statement is messed up. I am trying to figure out a way to compare consecutive digits WITHOUT using Integer class or String class. Any suggestions?

3
  • What's the problem with the current code? Commented Nov 3, 2016 at 11:04
  • 1
    You need to keep track of the max count. Right now your code forgets it whenever the count resets to 0. Commented Nov 3, 2016 at 11:06
  • @Tunaki The output is incorrect. It keeps on returning 0 unless it's a single digit number for which I have a separate if statement. Commented Nov 3, 2016 at 11:06

1 Answer 1

3

The problem with your code is that count keeps track of the current count, not of the highest count. You need to add a variable that tracks the highest count as well, and update it each time you process a digit, before resetting count back to zero.

Don't forget to update the highest count when you exit the loop, in case then-current count is greater than the previously found max.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I have editted my code slightly, but still the outputs are wrong.
@TheBolt That's because of the count1 += count; part. You should assign count1 the max of the old count1 and the new count.
Thanks! I tried out another thing but it's still incorrect :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.