Posted on

Description

Submission

class Solution {
public:
    vector<string> readBinaryWatch(int turnedOn) {
        vector<string> rets;

        for(int hour = 0; hour < 12; ++hour) {
            for(int minute = 0; minute < 60; ++minute) {
                if(__builtin_popcount(hour) + __builtin_popcount(minute) == turnedOn) {
                    stringstream ss;
                    ss << hour << ":" << setfill('0') << setw(2) << minute;
                    rets.push_back(ss.str());
                }
            }
        }

        return rets;
    }
};
class Solution {
public:
    vector<string> readBinaryWatch(int turnedOn) {
        vector<int> hours{8, 4, 2, 1};
        vector<int> minutes{32, 16, 8, 4, 2, 1};

        vector<string> rets;

        for(int i = 0; i <= turnedOn; ++i) {
            int j = turnedOn - i;

            for(int state1 = 0; state1 < (1 << hours.size()); ++state1) {
                if(__builtin_popcount(state1) != i) continue;
                int hour = 0;
                for(int i = 0; i < hours.size(); ++i) {
                        if((state1>>i)&1) hour += hours[i];
                }
                if(hour >= 12) continue;
                for(int state2 = 0; state2 < (1 << minutes.size()); ++state2) {
                    if(__builtin_popcount(state2) != j) continue;
                    
                    int minute = 0;

                    for(int i = 0; i < minutes.size(); ++i) {
                        if((state2>>i)&1) minute += minutes[i];
                    }
                    if(minute >= 60) continue;

                    // convert minute and hour to string
                    stringstream ss;
                    ss << hour << ":" << setfill('0') << setw(2) << minute;
                    rets.push_back(ss.str());
                }
            }
        }

        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *