Leetcode: 401. Binary Watch

这里我提出两种做法,一种呢就是把每个bit分开,这种写法很直接;一种是根据10bits的大小进行一次迭代,看哪些数字符合要求。

第一种方法:非常low

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> result;

        for(int h4 = 0; h4 <= 1; h4++)
            for(int h3 = 0; h3 <= 1; h3++)
                for(int h2 = 0; h2 <= 1; h2++)
                    for(int h1 = 0; h1 <= 1; h1++)
                        for(int m6 = 0; m6 <= 1; m6++)
                                for(int m5 = 0; m5 <= 1; m5++)
                                    for(int m4 = 0; m4 <= 1; m4++)
                                        for(int m3 = 0; m3 <= 1; m3++)
                                            for(int m2 = 0; m2 <= 1; m2++)
                                                for(int m1 = 0; m1 <= 1; m1++)
                                                {
                                                    if(m1+m2+m3+m4+m5+m6+h1+h2+h3+h4 == num)
                                                    {
                                                        int h = h1 + (h2 << 1) + (h3 << 2) + (h4 << 3);
                                                        int m = m1+ (m2<<1)+(m3<<2)+(m4<<3) + (m5<<4) + (m6<<5);
                                                        if(h < 12 && m <= 59) 
                                                        {
                                                            char str[20];
                                                            sprintf(str, "%d:%02d", h, m);
                                                            result.push_back(str);
                                                        }
                                                    }
                                                }
        return result;                                        
    }
};

第二种方法:好了一点点

class Solution {
public:
    static int count_one_num(int tmp)
    {
        int rel = 0;

        while(tmp)
        {
            rel += (tmp & 1);
            tmp  = tmp >> 1;  
        }

        return rel;
    }

    vector<string> readBinaryWatch(int num) {
        vector<string> result;

        int num_max = (11 << 6) | ((1 << 6) - 1);

        for(int i = 0; i < num_max; i++) 
        {
            int c = count_one_num(i);

            if(c == num)
            {
                int h = i >> 6;
                int m = i & 0x3f;

                if(m <= 59)
                {
                    char str[20];
                    sprintf(str, "%d:%02d", h, m);
                    result.push_back(str); 
                }    
            }
        }

        return result;                                        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值