File tree Expand file tree Collapse file tree 1 file changed +21
-6
lines changed Expand file tree Collapse file tree 1 file changed +21
-6
lines changed Original file line number Diff line number Diff line change @@ -26,15 +26,30 @@ private static int countBinaryOnes(int num) {
2626return count ;
2727}
2828
29+ // optimal code using DP
30+ public static int [] countBitsDP (int n ) {
31+ int [] ans = new int [n + 1 ];
32+ ans [0 ] = 0 ;
33+
34+ for (int index = 1 ; index <= n ; index ++) {
35+ if (index % 2 == 0 ) { // even
36+ ans [index ] = ans [index / 2 ];
37+ } else { // odd
38+ ans [index ] = 1 + ans [index / 2 ];
39+ }
40+ }
41+ return ans ;
42+ }
43+
2944public static void main (String [] args ) {
3045System .out .println (Arrays .toString (countBits (2 )));
3146System .out .println (Arrays .toString (countBits (5 )));
3247System .out .println (Arrays .toString (countBits (0 )));
48+
49+ System .out .println ("\n optimal\n " );
50+
51+ System .out .println (Arrays .toString (countBitsDP (2 )));
52+ System .out .println (Arrays .toString (countBitsDP (5 )));
53+ System .out .println (Arrays .toString (countBitsDP (0 )));
3354}
3455}
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