leetCode 338. Counting Bits | Dynamic Programming | Medium

简介:

338. Counting Bits


Given a non negative integer number num. For every numbers 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].

题目大意:

给一个数字,比如5,那么5之前所有的整数的每个二进制表示中1的个数。

思路:

数字 二进制表示 二进制中1的个数
0 0 0
1
1 1
2
10 1
3 11 2
4 100 1
5 101 2
6 110 2
7 111 3
8 1000 1
9 1001 2
10 1010 2
11 1011 3
12 1100 2
13 1101 3
14 1110 3
15 1111 4
16 10000 1
根据上面分析的到一个规律:每达到2的i次方,就会从第一个元素开始依次加1,赋值给当前元素到下一次达到2的i+1次方的元素。


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class  Solution {
public :
     vector< int > countBits( int  num) {
         vector< int > result;
         if (num == 0)
         {
             result.push_back(0);
             return  result;
         }
         if (num == 1)
         {
             result.push_back(0);
             result.push_back(1);
             return  result;
         }
         result.push_back(0);
         result.push_back(1);
         
         int  temp = 2;
         for ( int  i = 2; i <=num ; i++)
         {
             if (i == temp*2)
                 temp *= 2;
             result.push_back(result[i-temp] + 1);
         }
         return  result;
     }
};


本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1845319


相关文章
|
1月前
|
算法 搜索推荐 Java
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
16 3
|
1月前
|
存储 算法 Java
【经典算法】LeetCode 5: 最长回文子串(Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 5: 最长回文子串(Java/C/Python3实现含注释说明,Medium)
12 2
|
1月前
|
存储 缓存 算法
【经典算法】LeetCode 1143:最长公共子序列Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 1143:最长公共子序列Java/C/Python3实现含注释说明,Medium)
10 1
|
算法 测试技术
LeetCode 周赛 333,你管这叫 Medium 难度?
大家好,我是小彭。 上周是 LeetCode 第 333 场周赛,你参加了吗?这场周赛质量很高,但难度标得不对,我真的会谢。算法解题思维需要长时间锻炼,加入我们一起刷题吧~
91 0
|
算法 C++
LeetCode 338. Counting Bits
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
61 0
LeetCode 338. Counting Bits
【LeetCode98】验证二叉搜索树(medium)
二叉排序树的定义中注意不是左孩子小于当前结点,而是左子树上的所有结点值都小于当前结点,因此在递归遍历二叉树的同时需要保存结点权值的上界和下界——实现比较时不止比较子结点的值,也要与上下界比较。
87 0
【LeetCode98】验证二叉搜索树(medium)
|
C++
Leetcode-Medium 338. Counting Bits
Leetcode-Medium 338. Counting Bits
82 0
【LeetCode】Counting Bits(338)
  Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
88 0