LeetCode-Binary Watch
2017-01-20 本文已影响20人
sakuragi
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
}
}