Created
January 28, 2017 03:23
-
-
Save abatilo/46dab900f55630bb1ed0a10e9a36ba7e to your computer and use it in GitHub Desktop.
Binary watch
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
import java.util.*; | |
public class Solution { | |
private int numberOfOneBits(int num) { | |
int count = 0; | |
while (num != 0) { | |
if ((num & 1) == 1) { | |
++count; | |
} | |
num >>= 1; | |
} | |
return count; | |
} | |
public List<String> readBinaryWatch(int num) { | |
List<String> results = new ArrayList<>(); | |
Map<Integer, List<Integer>> map = new HashMap<>(); | |
for (int i = 0; i < 60; ++i) { | |
int bits = numberOfOneBits(i); | |
if (map.containsKey(bits)) { | |
map.get(bits).add(i); | |
} else { | |
List<Integer> possibilities = new ArrayList(); | |
possibilities.add(i); | |
map.put(bits, possibilities); | |
} | |
} | |
for (int i = 0; i < 4; ++i) { | |
int remainingBits = num - i; | |
for (int j = 0; j <= remainingBits; ++j) { | |
if ((i + j) != num) { continue; } | |
if (!map.containsKey(i)) { continue; } | |
for (int possibilityI : map.get(i)) { | |
if (!map.containsKey(j)) { continue; } | |
for (int possibilityJ : map.get(j)) { | |
if (possibilityI < 12 && possibilityJ < 61) { | |
results.add(possibilityI + ":" + (possibilityJ < 10 ? "0" + possibilityJ : possibilityJ)); | |
} | |
} | |
} | |
} | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment