Skip to content

Latest commit

 

History

History
33 lines (31 loc) · 889 Bytes

401. Binary Watch.md

File metadata and controls

33 lines (31 loc) · 889 Bytes

思路

由于分钟和小时都是有限且很小的,所以我们可以遍历一遍所有分钟,检查其二进制表示中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;
    }
};