Leecode学习——二进制手表

题目:二进制手表

Leecode学习——二进制手表_第1张图片Leecode学习——二进制手表_第2张图片

`#include<iostream>
#include 
#include
#include
using namespace std; 
   int count1(int n) {
        int res = 0;
        while (n != 0) {
            n = n & (n - 1);
            res++;
        }
        return res;
    }
    vector<string> readBinaryWatch(int num) {
        vector<string> res;
        vector<string>::iterator it;
        //直接遍历  0:00 -> 12:00   每个时间有多少1
        for (int i = 0; i < 12; i++) {
            for (int j = 0; j < 60; j++) {
                if (count1(i) + count1(j) == num) {
                    res.push_back(std::to_string(i)+":"+
                                  (j < 10 ? "0"+std::to_string(j) : to_string(j)));
                    
                }
            }
        }
         for (it =res.begin(); it!= res.end(); it++)
		  {
        //输出迭代器上的元素值
        cout << *it << " ";
    }
        return res;
    }
    //计算二进制中1的个数
int main()
{readBinaryWatch(1);
return 0;
}

从这个题解中我学到了很多,其中比较重要的就是那个用n=n&(n-1)来找出某数值的二进制形式中有多少个1,它循环执行多少次就代表那个二进制数值中有多少个1.

参考题解来自:

作者:ljj666
链接:https://leetcode-cn.com/problems/binary-watch/solution/cjian-jian-dan-dan-de-ji-xing-dai-ma-jie-jue-wen-t/
来源:力扣(LeetCode)

`

你可能感兴趣的:(C++程序题)