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.
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"]
Approach:
C++
#include <bits/stdc++.h>using namespace std;vector<string> readBinaryWatch(int num){vector<string> res;char str[10];for (int i = 0; i < 1 << 10; i++){int s = 0;for (int j = 0; j < 10; j++){if (i >> j & 1){s++;}}if (s == num){int a = i >> 6, b = i & 63;if (a < 12 && b < 60){string str = "";if (b < 10)str = str + to_string(a) + ":" + "0" +to_string(b);elsestr = str + to_string(a) + ":" +to_string(b);res.push_back(str);}}}return res;}int main(){int n = 1;vector<string> res = readBinaryWatch(n);cout << "[";for (int i = 0; i < res.size(); i++){cout << res[i];if (i != res.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment