-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathCountingBits.java
More file actions
40 lines (35 loc) · 827 Bytes
/
CountingBits.java
File metadata and controls
40 lines (35 loc) · 827 Bytes
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
//Author : Shobhit Behl (LC : shobhitbruh)
class Solution {
public int[] countBits(int n) {
int[] arr=new int[n+1];
for(int i=0;i<arr.length;i++){
int j=i;
int c=0;
while(j>0){
c++;
j^=(j&(~j+1));
}
arr[i]=c;
}
return arr;
}
}
// @Coding Decoded
class Solution {
// TC : O(n) // SC: O(n)
public int[] countBits(int num) {
// 0 ..n
int[] ans = new int[num + 1];
ans[0] = 0;
for(int i = 1; i <= num; i++){
// even in nature
if((i %2) == 0){
ans[i] = ans[i/2];
}else{
// i is odd
ans[i] = ans[i - 1] + 1;
}
}
return ans;
}
}