forked from onkardighe/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_0338_Counting_Bits.java
51 lines (43 loc) · 1008 Bytes
/
_0338_Counting_Bits.java
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
48
49
50
51
// https://leetcode.com/problems/counting-bits/
import java.util.Arrays;
public class _0338_Counting_Bits
{
public static void main(String[] args) {
int iNo = 5;
System.out.println(Arrays.toString(countBits(iNo)));
}
// UPDATED Solution O(n)
public static int[] countBits(int iNo)
{
int[] ans = new int[iNo+1];
ans[0] = 0;
for(int i = 1; i <= iNo; i++)
{
if((i & 1) == 0)
{
ans[i] = ans[i>>1];
}
else
{
ans[i] = ans[i>>1]+1;
}
}
return ans;
}
// PREVIOUS Solution O(n^2)
public static int[] oldCountBits(int iNo)
{
int[] ans = new int[iNo+1];
int bin;
for(int i = 0; i <= iNo; i++)
{
bin = i;
while(bin!=0)
{
bin = bin & bin-1;
ans[i]++;
}
}
return ans;
}
}