# Simple Python+Java

• Just go through the possible times and collect those with the correct number of one-bits.

Python:

``````def readBinaryWatch(self, num):
return ['%d:%02d' % (h, m)
for h in range(12) for m in range(60)
if (bin(h) + bin(m)).count('1') == num]
``````

Java:

``````public List<String> readBinaryWatch(int num) {
List<String> times = new ArrayList<>();
for (int h=0; h<12; h++)
for (int m=0; m<60; m++)
if (Integer.bitCount(h * 64 + m) == num)
return times;
}``````

• Did not get the * 64 ?

• @naineel2 My understanding is to differentiate hours and minutes by bit, as hours will occupy 4 bits, and minutes will occupy 6. Replace the line with "Integer.bitCount(h + m * 16) == num" also works.

• @naineel2

He means:
Integer.bitCount(m + (h << 6))

You could also do:
Integer.bitCount(m) + Integer.bitCount(h)

• So brilliant!!!

• @crystal_la Thanks

• @fuark3 Thanks for the help

• How you write the recursive coding? Like there are 4 elements in the hour list, and 6 elements in mins list. Then you choose i element in the hour list and choose num - i elements in mins list, when the total element are the same with num, then represent the result with time formatting.

• because your solution need O(n*n) time complicity, you can improve it? And can you rewrite it with recursion?

• @wzrthhj It's not O(N*N), instead it is O(1). The nested loop is 12 * 60 regardless of value of N.

• @lfzh123 said in Simple Python+Java:

It's not O(N*N), instead it is O(1)

It is O(N*N).

Every O(1) algorithm is also O(N*N).

• @StefanPochmann "h*64" what does it mean?I don't quite understand.

• This post is deleted!

• Really brilliant, man.

• Thanks. BTW,so awesome.

• Great use of list comprehension

• Nice solution. I came up similar idea, but I iterated all numbers rather than all times. Your solution is much concise and better than mine. Thanks.
C++ version: https://discuss.leetcode.com/topic/61611/c-0ms-bit-manipulation

• Brilliant solution!

• I was wondering what was the simple idea I was missing.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.