-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountLargestGroup.java
77 lines (57 loc) · 1.69 KB
/
CountLargestGroup.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.*;
class CountLargestGroup {
public static void main(String[] args) {
int[] tests = {13, 2, 15, 24};
for(int test: tests) {
System.out.printf("countLargestGroup(%d) = %d\n", test, countLargestGroup(test));
}
}
private static int countLargestGroup(int n) {
HashMap<Integer, Integer> digitTotals = new HashMap<Integer, Integer>();
for(int i = 0; i <= n; i++) {
int tot = digitTotal(i);
boolean counted = digitTotals.containsKey(tot);
if(counted == true) {
int curVal = digitTotals.get(tot);
curVal++;
digitTotals.put(tot, curVal);
} else {
digitTotals.put(tot, 1);
}
}
int largestCount = 0;
int i = 0;
Iterator dtIterator = digitTotals.entrySet().iterator();
while (dtIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry)dtIterator.next();
// int marks = ((int)mapElement.getValue() + 10);
// System.out.println(mapElement.getKey() + " : " + marks);
int thisVal = (int)mapElement.getValue();
if(i == 0) {
largestCount = thisVal;
} else if(thisVal > largestCount) {
largestCount = thisVal;
}
}
int groupCount = 0;
Iterator dtIterator2 = digitTotals.entrySet().iterator();
while (dtIterator2.hasNext()) {
Map.Entry mapElement = (Map.Entry)dtIterator2.next();
int thisVal = (int)mapElement.getValue();
if(thisVal == largestCount) {
groupCount++;
}
}
return groupCount;
}
private static int digitTotal(int x) {
int tot = 0;
int rem = 0;
while(x > 0) {
rem = x % 10;
x = x / 10;
tot = tot + rem;
}
return tot;
}
}