p338

LeetCode P338 Counting Bits 题解

1.题目:

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.

题意:

输入一个数字num
返回一个数组
这个数组是0至num中所有数字的二进制表达中有几个1
希望空间复杂度和时间复杂度不超过O(n)

2.解题思路:

先写出前几个数的二进制进行分析:
0 0 0
1 1 1
2 10 1
3 11 2
4 100 1
5 101 2

首先我们可以知道2的n次方的二进制中1的个数都是1
其次在这个基础上分析 其它的数a=小于a的最大二进制数b+(b-a)
则它的二进制中1的个数=1+n(b-a)

3.代码


[title] [] [url] [link text]
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
package leetcode;

import java.util.Scanner;

/**
*
* @author ZhangMengRou
*
*/

public class P338 {

public static void main(String[] args) {

int num;
Scanner in = new Scanner(System.in);
num = Integer.parseInt(in.nextLine());
int[] a = countBits(num);
for (int i = 0; i < num + 1; i++) {
System.out.print(i+"is"+a[i]+"\n");
System.out.println(Integer.toBinaryString(i)+"\n");
}
}

public static int[] countBits(int num) {
int[] ans = new int[num + 1];
ans[0] = 0;
if (num == 0) {

return ans;
}
ans[1] = 1;
int two = 2;
for (int i = 2; i < num + 1; i++) {
if (i == two) {
ans[i] = 1;
two = two * 2;
} else {
ans[i] = 1 + ans[i - two / 2];
}
}
return ans;
}
}



4.一些总结:递推思想,还有很多更有趣更奇妙的解法~待续