File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=338 lang=java
3
+ *
4
+ * [338] Counting Bits
5
+ *
6
+ * https://leetcode.com/problems/counting-bits/description/
7
+ *
8
+ * algorithms
9
+ * Medium (63.91%)
10
+ * Total Accepted: 151.8K
11
+ * Total Submissions: 237.5K
12
+ * Testcase Example: '2'
13
+ *
14
+ * Given a non negative integer number num. For every numbers i in the range 0
15
+ * ≤ i ≤ num calculate the number of 1's in their binary representation and
16
+ * return them as an array.
17
+ *
18
+ * Example 1:
19
+ *
20
+ *
21
+ * Input: 2
22
+ * Output: [0,1,1]
23
+ *
24
+ * Example 2:
25
+ *
26
+ *
27
+ * Input: 5
28
+ * Output: [0,1,1,2,1,2]
29
+ *
30
+ *
31
+ * Follow up:
32
+ *
33
+ *
34
+ * It is very easy to come up with a solution with run time
35
+ * O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a
36
+ * single pass?
37
+ * Space complexity should be O(n).
38
+ * Can you do it like a boss? Do it without using any builtin function like
39
+ * __builtin_popcount in c++ or in any other language.
40
+ *
41
+ */
42
+ class Solution {
43
+ public int [] countBits (int num ) {
44
+ int [] count = new int [num + 1 ];
45
+ for (int i = 1 ; i <= num ; i ++) {
46
+ count [i ] = count [i & (i -1 )] + 1 ;
47
+ }
48
+ return count ;
49
+ }
50
+ }
51
+
You can’t perform that action at this time.
0 commit comments