69. The algorithm is simple and swift binary watch

Binary watch has four top LED for hour (0-11), six bottom LED for minutes (0-59).

Each LED represents a 0 or 1, the least significant bit on the right.

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

Given a non-negative integer n represents the number of lit LED current returns all possible time.

Case:

输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
 

Precautions:

Output order is not required.
Hours will not start with zero, such as "01:00" is not allowed, should be "1:00."
Minutes must consist of two digits, might start with zero, such as "10: 2" is invalid, it should be "10:02."

solution:

 func readBinaryWatch(_ num: Int) -> [String] {
                var res = [String]()
                //直接遍历  0:00 -> 12:00   每个时间有多少1
        for  i  in 0..<12 {
            for  j  in 0..<60{
                if (count1(i) + count1(j) == num) {
                   res.append(String(i) + ":" + (j < 10 ? "0" + String(j) : String(j)))
                }
            }
        }
        return res;
    }
    
    /**
     * 计算二进制中1的个数
     * @param n
     * @return
     */
    func count1(_ n: Int) -> Int {
        var n = n
        var res = 0
        while (n != 0) {
            n = n & (n - 1);
            res += 1;
        }
        return res;
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93159824