C++ bit manipulation, simple solution


  • 0
    class Solution {
    public:
        string to_time(bitset<10>& st) {
            int hour = 0, min = 0;
            for (int i = 0, k = 1; i < 4; i++, k <<= 1)
                if (st[i])
                    hour |= k;
            for (int i = 4, k = 1; i < 10; i++, k <<= 1)
                if (st[i])
                    min |= k;
            if (hour >= 12 || min >= 60) // check
                return "NULL";
            return to_string(hour) + ":" + (min < 10 ? ("0" + to_string(min)) : to_string(min));
            
        }
        void dfs(vector<string>& res, bitset<10>& st, int num, int cur) {
            if (num == 0 || cur >= 10) { // no light left or move to the end
                if (num == 0 && to_time(st) != "NULL")
                    res.push_back(to_time(st));
                return;
            }
            dfs(res, st, num, cur + 1);
            st.flip(cur); // change 
            dfs(res, st, num - 1, cur + 1);
            st.flip(cur); // back
        }
        vector<string> readBinaryWatch(int num) {
            vector<string> res;
            bitset<10> st;
            dfs(res, st, num, 0);
            return res;
        }
    };
    

Log in to reply
 

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