Created
June 18, 2021 08:35
-
-
Save bijay-shrestha/216c7083ee45ba4e64a0bfa9be09ce28 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.basic.practice; | |
import lombok.extern.slf4j.Slf4j; | |
@Slf4j | |
public class HighestOccurringDigitInNumber { | |
public static void main(String[] args) { | |
// int number = 1223412; | |
int number = 122341112; | |
log.info("Finding highest occurring digit in a number {}.", number); | |
log.info("Actual Result: {}", findHighestOccurringDigit(number)); | |
} | |
static int findHighestOccurringDigit(int n) { | |
int result = 0; | |
int count = 0; | |
int maxCount = 1; | |
for (int i = 0; i <= 9; i++) { | |
count = countOccurrence(n, i); | |
if (count >= maxCount) { | |
maxCount = count; | |
result = i; | |
} | |
} | |
return result; | |
} | |
static int countOccurrence(int n, int i) { | |
int count = 0; | |
while (n > 0) { | |
if (n % 10 == i) { | |
count++; | |
} | |
n = n / 10; | |
} | |
return count; | |
} | |
} |
coder-shankar
commented
Jul 8, 2022
package problems;
public class MostFrequentNumber {
public static void main(String[] args) {
int number = 1223412122;
String str = "1223412122444444";
mostFrequentNumber(number);
mostFrequentString(str);
}
private static int mostFrequentString(String str) {
int[] frequency = new int[10];
for (int i = 0; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
frequency[digit]++;
}
int maxFrequent = 0;
int index = 0;
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > maxFrequent) {
maxFrequent = frequency[i];
index = i;
}
}
System.out.println("max frequent string is " + index + " with frequency of " + maxFrequent);
return index;
}
private static int mostFrequentNumber(int number) {
int[] frequency = new int[10];
while (number > 0) {
int digit = number % 10;
number /= 10;
frequency[digit]++;
}
int index = 0;
int maxFrequency = 0;
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > maxFrequency) {
maxFrequency = frequency[i];
index = i;
}
}
System.out.println("max frequent number is " + index + " with frequency of " + maxFrequency);
return index;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment