Java recursion O(n) time O(1) extra space 4ms


  • 5
    K
    public class Solution {
        public int[] countBits(int num) {
            int[] result = new int[num+1];
            result[0] = 0;
            for(int i=1;i<=num;i++){
                result[i] = result[i/2] + i%2;
            }
            return result;
        }
    }

  • 0
    7

    excellent!!!


  • 0
    Y

    My solution is 90% same with yours. The only difference is, I didn't set result[0] = 0 because the default value of element data in array of int is 0. If you delete that line, you still get correct result.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.