LeetCode-Binary Watch

https://leetcode.com/problems/binary-watch/
题目的大致意思是这样的:
首先介绍一下Binary Watch
表盘上10个灯,开和关分别代表1和0.
前4个灯表示小时,后6个灯表示分钟数。
现在给出亮的灯数n,求出可以表示的时间。
直接上代码

先来一份C++的代码

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> res;
        for(int h=0; h<12; h++)
        for(int m=0; m<60; m++)
            if (bitset<10>(h<<6|m).count() == num)
                res.push_back(to_string(h)+(m<10?":0":":")+to_string(m));
        return res;
        
    }
};

接着我又用swift 重写了,由于没有找到swift的bitset类,所以直接枚举出了所有的时钟和分钟数字。

class Solution {
    func readBinaryWatch(_ num: Int) -> [String] {
        var hour:[[String]] = [["0"],["1","2","4","8"],["3","5","6","9","10"],["7","11"]]
        var minute:[[String]] = [["00"], //1
            ["01", "02", "04", "08", "16", "32"], //6
            ["03", "05", "06", "09", "10", "12", "17", "18", "20", "24", "33", "34", "36", "40", "48"], //15
            ["07", "11", "13", "14", "19", "21", "22", "25", "26", "28", "35", "37", "38", "41", "42", "44", "49", "50", "52", "56"], //20
            ["15", "23", "27", "29", "30", "39", "43", "45", "46", "51", "53", "54", "57", "58"], //14
            ["31", "47", "55", "59"]]
        var res:[String] = [String]()
        for i in 0...3 {
            for j in 0...5 {
                if(i + j == num) {
                    for str1 in hour[i] {
                        for str2 in minute[j] {
                            res.append(str1+":"+str2)
                        }
                    }
                }
            }
        }
        return res
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • My code: 并不是一道难题,但是觉得应该是 medium,因为也不是瞬秒的。整体过程写起来,至少得10分钟吧...
    Richardo92阅读 562评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,276评论 4 61
  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS 目录 UI下拉刷新模糊效果A...
    袁俊亮技术博客阅读 12,004评论 9 105
  • 感恩今天的天气炎热,大大的太阳,正好可以把给悠悠上学准备的被褥拿出来晒晒,既软活,又消了毒。 感恩今天送悠悠上学,...
    武丹yoyo阅读 296评论 0 0