Binary Watch (easy)

update Jan 26, 2018 23:15

LeetCodearrow-up-right A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).

Each LED represents a zero or one, with the least significant bit on the right.

Watch Picture here. From LeetCode website

For example, the above binary watch reads "3:25".

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

Example:

Note:

  1. The order of output does not matter.

  2. The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".

  3. The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".

Basic Idea:

按顺序枚举每个时刻,计数该时刻二进制表示中的 1 的个数,如果和input相等,将其 format 成相应格式的 string 加入 result list 中;

  • Java Code:

update May 8,2018 16:24

C++ Code:

注意 c++ 中string format 需要使用字符数组和 sprintf() 配合, 然后可以用 string(char[]) 直接生成string。