File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ package easy ;
2+
3+ import java .util .Arrays ;
4+
5+ public class CountingBits338 {
6+
7+ public static int [] countBits (int n ) {
8+ int [] ans = new int [n + 1 ];
9+
10+ for (int i = 0 ; i <= n ; i ++) {
11+ ans [i ] = countBinaryOnes (i );
12+ }
13+ return ans ;
14+ }
15+
16+ private static int countBinaryOnes (int num ) {
17+ int count = 0 ;
18+ int mask = 1 ;
19+
20+ while (num != 0 ) {
21+ if ((num & mask ) != 0 )
22+ count ++;
23+
24+ num = num >> 1 ; // right shift
25+ }
26+ return count ;
27+ }
28+
29+ public static void main (String [] args ) {
30+ System .out .println (Arrays .toString (countBits (2 )));
31+ System .out .println (Arrays .toString (countBits (5 )));
32+ System .out .println (Arrays .toString (countBits (0 )));
33+ }
34+ }
35+
36+ /* output:
37+ [0, 1, 1]
38+ [0, 1, 1, 2, 1, 2]
39+ [0]
40+ */
You can’t perform that action at this time.
0 commit comments