• LeetCode Binary Watch


    原题链接在这里:https://leetcode.com/problems/binary-watch/

    题目:

    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.

    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:

    Input: n = 1
    Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

    Note:

    • The order of output does not matter.
    • The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
    • 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".

    题解:

    上面4个表示小时,下面6个表示分钟,把小时向左移动6位 | 分钟就是二进制表示。二进制表示中 1 bit的个数等于num时就把这个组合加到结果中。

    可以用Number of 1 Bits 或者Integer.bitCount()求出1 bit的个数.

    Time Complexity: O(1), 12 * 60 * O(1). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public List<String> readBinaryWatch(int num) {
     3         List<String> res = new ArrayList<String>();
     4         for(int h = 0; h<12; h++){
     5             for(int m = 0; m<60; m++){
     6                 if(Integer.bitCount(h<<6 | m) == num){
     7                     res.add(String.format("%d:%02d", h, m));
     8                 }
     9             }
    10         }
    11         return res;
    12     }
    13 }
  • 相关阅读:
    topK问题 前K个高频元素 leetcode692
    反转链表 leetcode206
    关于IO多路复用的简单整理
    两数之和 leetcode1
    使用 jenkins 发布 前端 项目
    CentOS7 部署 nacos 集群
    JWT
    keepalived 的 unicast 单播模式
    使用 keepalived 高可用 nginx
    翻转二叉树 leetcode226
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6269451.html
Copyright © 2020-2023  润新知