Open azl397985856 opened 6 months ago
class Solution: def readBinaryWatch(self,num: int) -> list: def count1(n): return bin(n).count('1')
res = []
# Directly iterate from 0:00 to 11:59, count the number of 1s in the binary representation
for i in range(12):
for j in range(60):
if count1(i) + count1(j) == num:
# Format the time correctly with leading zeros for minutes less than 10
res.append(f"{i}:{j:02d}")
return res
class Solution {
public:
vector
class Solution:
def readBinaryWatch(self, turnedOn: int) -> List[str]:
minute = [1, 2, 4, 8, 16, 32]
hour = [1, 2, 4, 8]
h_len, m_len = len(hour), len(minute)
ans = []
def time(combi, led, start):
if led == 0:
if combi[1] < 10:
ans.append(str(combi[0]) + ':0' + str(combi[1]))
else:
ans.append(str(combi[0]) + ':' + str(combi[1]))
else:
for i in range(start, h_len + m_len):
if i < h_len:
combi[0] += hour[i]
if combi[0] <= 11:
time(combi, led - 1, i + 1)
combi[0] -= hour[i]
else:
combi[1] += minute[i - h_len]
if combi[1] <= 59:
time(combi, led - 1, i + 1)
combi[1] -= minute[i - h_len]
cur = 2 * [0]
time(cur, turnedOn, 0)
return ans
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: ans = [] for a in range(12): for b in range(60): if (bin(a) + bin(b)).count('1') == turnedOn: ans.append(str(a) +":" + str(b).rjust(2, '0')) return ans
/*
* @lc app=leetcode.cn id=401 lang=javascript
*
* [401] 二进制手表
*/
// @lc code=start
/**
* @param {number} turnedOn
* @return {string[]}
*/
var readBinaryWatch = function (turnedOn) {
const result = [];
for (let h = 0; h < 12; h++) {
for (let m = 0; m < 60; m++) {
if (
h.toString(2).split(0).join("").length +
m.toString(2).split(0).join("").length ===
turnedOn
) {
const minuteNum = m < 10 ? `0${m}` : m;
result.push(`${h}:${minuteNum}`);
}
}
}
return result;
};
// @lc code=end
401. 二进制手表
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/binary-watch/
前置知识
暂无
题目描述