2 C++ solutions


  • 3
    K

    straight forward

    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)
                    {
                        string str=to_string(h)+":";
                        str+=(m<10)?("0"+to_string(m)):to_string(m);
                        res.push_back(str);
                    }
            return res;
        }
    };
    

    combination

    class Solution {
    public:
        vector<string> readBinaryWatch(int num) {
            vector<vector<int>>hour(5),min(7);
            for(int i=0;i<12;++i)
            {
                int n=bitset<4>(i).count();
                hour[n].push_back(i);
            }
            for(int i=0;i<60;++i)
            {
                int n=bitset<6>(i).count();
                min[n].push_back(i);
            }
            vector<string>res;
            for(int i=0;i<=num&&i<=4;++i)
                for(int j=0;j<hour[i].size();++j)
                    for(int k=0;num-i<=6&&k<min[num-i].size();++k)
                    {
                        string str=to_string(hour[i][j])+":";
                        if(min[num-i][k]<10)
                            str+="0";
                        str+=to_string(min[num-i][k]);
                        res.push_back(str);
                    }
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.