A binary watch has 4 LEDs to represent the hours (0 to 11) and 6 LEDs to represent the minutes (0 to 59). Each LED represents a bit that can either be 0 or 1.
For example, the binary representation of the time “3:25” would be:
Given a non-negative integer turnedOn
which represents the number of LEDs that are currently on, return all possible times the watch could represent.
turnedOn
?
turnedOn
is 10 because there are exactly 10 LEDs in total (4 for hours and 6 for minutes).h
does not have leading zeros and mm
always has exactly two digits.turnedOn
.turnedOn
, format the time and add it to the results.#include <iostream>
#include <vector>
#include <string>
#include <bitset>
using namespace std;
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result;
for (int hours = 0; hours < 12; ++hours) {
for (int minutes = 0; minutes < 60; ++minutes) {
// Count the number of 1s in hours and minutes.
if (bitset<10>(hours).count() + bitset<10>(minutes).count() == turnedOn) {
// Format the time as h:mm
result.push_back(to_string(hours) + (minutes < 10 ? ":0" : ":") + to_string(minutes));
}
}
}
return result;
}
// Helper function to print the vector of strings
void printTimes(vector<string>& times) {
for (const auto& time : times) {
cout << time << " ";
}
cout << endl;
}
int main() {
vector<string> times;
int turnedOn = 1;
// Test the function with turnedOn = 1
times = readBinaryWatch(turnedOn);
printTimes(times);
return 0;
}
bitset
, which takes constant time.Therefore, the time complexity is O(1), considering the constant number of iterations (12 * 60 = 720
).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?