Java solution using String manipulation

  • 0
    public int[] countBits(int num) {
            int[] res=new int[num+1];
            for(int i=num;i>=0;i--)
                String temp=Integer.toBinaryString(num);
            return res;
    • Using Integer.toBinaryString gets every number's binary representation
    • Using String.replace() to eliminate all the "0" characters
    • The length of left string is the number of 1's

Log in to reply

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