-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Watch.java
55 lines (40 loc) · 1.61 KB
/
Binary Watch.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
// https://leetcode.com/problems/binary-watch/
class Solution {
public int countOnes(String strToInspect) {
// OBJECTIVE: Count how many times "1" appears in string
int counter = 0;
for (int i=0; i<strToInspect.length(); i++) {
if (strToInspect.charAt(i) == '1') {
counter++;
}
}
return counter;
}
public List<String> readBinaryWatch(int turnedOn) {
// Create a list
List<String> combo = new ArrayList();
// Iterate range
for (int hour=0; hour<12; hour++) {
for (int minute=0; minute<60; minute++) {
// Convert hour and minute into binary form
String curTime = Integer.toBinaryString(hour) + Integer.toBinaryString(minute);
// Count how many 1's are in curTime
int numOfOnes = countOnes(curTime);
if (numOfOnes == turnedOn) {
// Add hour to string
String tmp = Integer.toString(hour) + ":";
// Add padding to 0
if (minute < 10) {
tmp += "0" + Integer.toString(minute);
}
else {
tmp += Integer.toString(minute);
}
// Add acceptable time to list
combo.add(tmp);
}
}
}
return combo;
}
}