首页 > 其他 > 详细

[LeetCode] 338. Counting Bits

时间:2020-05-29 09:12:33      阅读:48      评论:0      收藏:0      [点我收藏+]

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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

比特位计数。题意是给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。如上第二个例子,如果input是5,那么从0到5,每个数字转换成二进制之后,包含的1的个数就是0,1,1,2,1,2

0 - 0000

1 - 0001

2 - 0010

3 - 0011

4 - 0100

5 - 0101

既然是问二进制数中包含的1的个数,不难发现二进制数有如下规律

  • 如果i是奇数,那么i和i + 1中1的数目只差一个,比如2和3;
  • 如果i是偶数,那么i中包含的1的个数跟i / 2相同,因为某个数字乘以2就是左移一位,除以2就是右移一位

有了这个规律,代码就比较直观了。设dp[i]是第i个数字包含的1的个数。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] countBits(int num) {
 3         int[] dp = new int[num + 1];
 4         dp[0] = 0;
 5         for (int i = 1; i <= num; i++) {
 6             if (i % 2 == 0) {
 7                 dp[i] = dp[i / 2];
 8             } else {
 9                 dp[i] = dp[i - 1] + 1;
10             }
11         }
12         return dp;
13     }
14 }

 

LeetCode 题目总结

[LeetCode] 338. Counting Bits

原文:https://www.cnblogs.com/cnoodle/p/12985062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!