【LeetCode】Counting Bits 解题报告

来源:互联网 发布:c语言取反加一 编辑:程序博客网 时间:2024/05/19 13:09

【LeetCode】Counting Bits 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/counting-bits/#/description

题目描述:

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].

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.

Ways

这个题用DP的方法。把第i个数分成两种情况,如果i是偶数那么,它的二进制1的位数等于i/2中1的位数;如果i是奇数,那么,它的二进制1的位数等于i-1的二进制位数+1,又i-1是偶数,所以奇数i的二进制1的位数等于i/2中二进制1的位数+1. 所以上面的这些可以很简单的表达成answer[i] = answer[i >> 1] + (i & 1)

public class Solution {    public int[] countBits(int num) {        int[] answer = new int[num+1];        answer[0] = 0;        for(int i = 1; i < answer.length; i++){            answer[i] = answer[i >> 1] + (i & 1);        }        return answer;    }}

Date

2017 年 4 月 25 日

0 0