Thursday, December 21, 2017

maxOccurDigit

Question :

Write a function named maxOccurDigit that returns the digit that occur the most. If there is no such digit, it will return -1. For example maxOccurDigit(327277) would return 7 because 7 occurs three times in the number and all other digits occur less than three times. Other examples:
maxOccurDigit(33331) returns 3
maxOccurDigit(3232, 6) returns -1
maxOccurDigit(5) returns 5
maxOccurDigit(-9895) returns 9

The function signature is

maxOccurDigit(int n)

Solution:


public static int maxOccurDigit(int n)
        {

         int rem1 = 0, count = 0, rem2 = 0, 
         temp = 0,maxCount = 0, maxNumber = 0;

            if (n < 0)
                n = -1 * n;
            while (n != 0)
            {
                rem1 = n % 10;
                count = 1;
                temp = n = n / 10;
                while (temp != 0)
                {
                    rem2 = temp % 10;
                    temp = temp / 10;
                    if (rem1 == rem2)
                    {
                        count++;
                    }
                }
                if (maxCount < count)
                {
                    maxCount = count;
                    maxNumber = rem1;
                }
                else if (maxCount == count)
                {
                    return -1;
                }
            }
            return maxNumber;
        }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More