二进制手表

原题在这里:

概述:

  给定4位和6位二进制位,分别用于表示数字[0,11],[0,59],问有n位二进制生效时候所表示的时间字符串数组。

analyse:

  1.直接思路就是dfs暴力构造了,但是这就增加了本题的难度,但是我还是写出来了,问题不大。

code:

 

class Solution
{
    vector<int> num;
    void get_num(int x, int y, int z, int n, int m) //二进制长度,当前i,当前数值, 当前选用个数
    {
        if (x == y || n == 0)
        {
            if (n == 0 && z < m)
                num.emplace_back(z);
            return;
        }
        get_num(x, y + 1, z, n, m);
        get_num(x, y + 1, z + (int)pow(2, x - y - 1), n - 1, m);
    }
    vector<int> read(int x, int y, int z, int n, int m)
    {
        num.clear();
        get_num(x, y, z, n, m);
        return num;
    }
    string ch(int x, bool pd)
    {
        if (x == 0)
            return pd ? "00" : "0";
        string ans;
        while (x)
        {
            ans = (char)(x % 10 + '0') + ans;
            x /= 10;
        }
        return ans.size() > 1 ? ans : (pd ? "0" : "") + ans;
    }
    void pr(vector<int> num)
    {
        for (int i : num)
            cout << i << ' ';
        cout << endl;
    }

public:
    vector<string> readBinaryWatch(int turnedOn)
    {
        int n = turnedOn;
        vector<string> ans;
        for (int i = 0; i <= 4; ++i)
        {

            for (int j = 0; j <= 6; ++j)
            {
                if (i + j != n)
                    continue;
                //数组转多个字符串匹配
                vector<int> p = read(4, 0, 0, i, 12);
                vector<int> q = read(6, 0, 0, j, 60);
                // cout << i << " , " << j << "输出两数组如下:" << endl;
                // pr(p);
                // pr(q);
                for (int y : q)
                    for (int x : p)
                        ans.emplace_back(ch(x, false) + ":" + ch(y, true));
            }
        }
        // sort(ans.begin(),ans.end());
        return ans;
    }
};
暴力构造

 

多动脑子还是好的,这个题我就属于不懂变通了。

  2.逆向思维,遍历时间检验当前时间的二进制位是否符号n位。

code:

class Solution
{
    int gn(int x)
    {
        int ans = 0;
        while (x)
            x = x & (x - 1), ans++;
        return ans;
    }
    string ch(int x)
    {
        if (x == 0)
            return "0";
        string ans;
        while (x)
        {
            ans = (char)(x % 10 + '0') + ans;
            x /= 10;
        }
        return ans;
    }

public:
    vector<string> readBinaryWatch(int turnedOn)
    {
        int n = turnedOn;
        vector<string> ans;
        for (int i = 0; i < 12; ++i)
        {
            for (int j = 0; j < 60; ++j)
            {
                if (gn(i) + gn(j) == n)
                {
                    string p = ch(i);
                    string q = ch(j);
                    if (q.length() < 2)
                        q = "0" + q;
                    ans.emplace_back(p + ":" + q);
                }
            }
        }
        return ans;
    }
};

 

【Over】

posted @ 2022-04-02 14:27  Renhr  阅读(33)  评论(0编辑  收藏  举报