zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    VisualVM工具的使用
    jstack的使用
    JVM内存溢出的定位与分析
    初识JVM
    JVM运行参数
    VIM 常用命令
    python3 简单抓取图片2
    python3 抓取图片
    node.js GET 请求简单案例
    node.js 爬虫
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6269451.html
Copyright © 2011-2022 走看看