338. Counting Bits
Description
Given a non-negative integer number num. For every number i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
题目大概意思是,=:给定一个非负整数num,要求输出从0到num中每个数二进制中1的个数,例如0二进制中1的个数为0,1二进制中1的个数为1,2二进制中1的个数为1,3二进制中1的个数为2。如果num=3,则输出[0,1,1,2]
my program
class Solution {
public:
int Count(int num)
{
int n = 0;
while (num)
{
++n;
num = num & (num -1);
}
return n;
}
vector<int> countBits(int num) {
vector<int> result;
for (int i=0; i<=num; ++i)
{
result.push_back(Count(i));
}
return result;
}
};
Submission Details
15 / 15 test cases passed.
Status: Accepted
Runtime: 73 ms
You are here!
Your runtime beats 51.45% of cpp submissions.
评价:中规中矩的方法,一个计算输入数二进制中1的个数的函数,从0循环到num将每个数中的1的个数分别压入vector result 中,最后返回结果数组。
other better algorithm
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for(int i=1; i<=num; ++i)
ret[i] = ret[i>>1] + i%2;
return ret;
}
};
用到了动态规划。
数组中存储了之前的结果,①当前的i二进制中1的个数等于i&(i-1)二进制中的个数再+1;
或者是②i二进制中1的个数等于i/2二进制的个数再+i%2(即如果i是偶数,那么i二进制中1的个数就等于i/2二进制中1的个数,如果i是奇数,那么i二进制的个数就等于i/2二进制中个数再+1);