The Bolt
The Bolt

Reputation: 121

Java- working with an integer

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?

Upvotes: 1

Views: 715

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

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.

Upvotes: 3

Related Questions