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)
Corrected Solution:
public static int maxOccurDigit(int n) { int rem1 = 0, count = 0, rem2 = 0, temp = 0, maxCount = 0, maxNumber = 0; bool flag = false; 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; flag = true; } else if (maxCount == count) { flag = false; } } if (!flag) return -1; return maxNumber; }
yo mildaina, try for 7775656
ReplyDeleteThis is how it should had been done:
ReplyDeletepublic static int maxOccurDigit(int n){
if(n<0) n=-n;
int result = 0, maxCount = 0;
boolean flag = false;
for(int i=0; i<=9; i++){
int count = 0;
int temp = n;
while(temp!=0){
if(temp%10==i) count++;
temp/=10;
}
if(count>maxCount){
flag=true;
maxCount=count;
result=i;
} else if(count==maxCount){
flag=false;
}
}
if(!flag) return -1;
return result;
}
thank you.i think now above code works
Deletestatic int maxOccurDigit(int n) {
ReplyDeleteint tempNum = n;
if (tempNum < 0)
tempNum = -tempNum;
int[] count = new int[10];
while (tempNum != 0) {
int rem = tempNum % 10;
count[rem] = count[rem] + 1;
tempNum = tempNum / 10;
}
int maxCount = count[0];
int digit = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
digit = i;
} else if (count[i] == maxCount)
digit = -1;
}
return digit;
}
Related question https://drive.google.com/file/d/1wcsZnfPi4YMqVLCXlFtQFc9rDPP_oE5I/view?usp=sharing
ReplyDeleteMy solution
https://replit.com/@kchemutai/hasSingleMode#Main.java