Skip to content

Latest commit

 

History

History
35 lines (32 loc) · 893 Bytes

401.md

File metadata and controls

35 lines (32 loc) · 893 Bytes

401. Binary Watch

Solution 1 (time O(1), space O(1))

class Solution {
public:
    vector<string> readBinaryWatch(int turnedOn) {
        vector<string> ans;
        for (int i = 0; i < 12; i++) {
            for (int j = 0; j < 60; j++) {
                if (count_ones(i) + count_ones(j) == turnedOn) {
                    if (j < 10) {
                        string cur_ans = to_string(i) + ":0" + to_string(j);
                        ans.push_back(cur_ans);
                    } else {
                        string cur_ans = to_string(i) + ":" + to_string(j);
                        ans.push_back(cur_ans);
                    }
                }
            }
        }
        return ans;
    }

    int count_ones(int num) {
        int ans = 0;
        while (num > 0) {
            ans += (num % 2);
            num /= 2;
        }
        return ans;
    }
};