LeetCode/solutions/401. Binary Watch.md
2022-11-22 23:04:43 +08:00

889 B
Raw Blame History

401. Binary Watch

思路

由于分钟和小时都是有限且很小的所以我们可以遍历一遍所有分钟检查其二进制表示中1的个数即可。是个简单题不要考虑太复杂。

C++

class Solution {
private:
    int bitCount(int num){
        int res = 0;
        while(num > 0){
            res += (num % 2);
            num /= 2;
        }
        return res;
    }
public:
    vector<string> readBinaryWatch(int turnedOn) {
        vector<string>res;
        for(int i = 0; i < 12; i++){
            for(int j = 0; j < 60; j++){
                if(bitCount(i) + bitCount(j) == turnedOn){
                    res.push_back(
                        to_string(i) + (j < 10 ? ":0" : ":") + to_string(j)
                    );
                }
            }
        }
        return res;
    }
};