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


相关文章
|
算法 测试技术
LeetCode 周赛 333,你管这叫 Medium 难度?
大家好,我是小彭。 上周是 LeetCode 第 333 场周赛,你参加了吗?这场周赛质量很高,但难度标得不对,我真的会谢。算法解题思维需要长时间锻炼,加入我们一起刷题吧~
84 0
LeetCode: 2_Add Two Numbers | 两个链表中的元素相加 | Medium
题目: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit.
885 0
LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area. For example, given the following matrix: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Return 4. 解题思路:   这种包含最大、最小等含优化的字眼时,一般都需要用到动态规划进行求解。
1087 0
|
存储 人工智能
LeetCode:1_Two_Sum | 两个元素相加等于目标元素 | Medium
题目: Given an array of integers, find two numbers such that they add up to a specific target number.
820 0

热门文章

最新文章