Leetcode Hangout Essay

Today, my classmate introduced a foreign interview brushing question website, similar to the domestic nine degrees, called Leetcode (children's shoes to find a job can go shopping), I wandered and made a question, the questions are as follows:
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. The general
idea is to find the number of 1 in the binary numbers from 0 to n. The general idea of ​​solving the problem is to group the requested array, and divide the converted binary digits into the same group, such as 2, 3 group, 4, 5, 6, 7 group, etc., mainly to obtain group The number of the group header element, such as 2, 4, 4, etc. Then you can get the number of 1s in the current grouped binary number by the number of 1s in the previously grouped binary number, such as 2, 4, and 8. . . The number of 1s in the converted binary is 0 plus the number of 1s in the converted binary, 1, 3, 5, and 9. . . The number of 1s in the converted binary is 1 plus 1 in the converted binary, and so on. The number of 1s in the currently converted binary can be obtained by adding 1 to the previously obtained number. The posted code is as follows:

public class Solution {
    public int[] countBits(int num) {
        int st1=2;
        int st2=2;
        int[] ret=new int[num+1];
        ret[0]=0;
        if(num>0) ret[1]=1;
        for(int i=2;i<=num;i++){
            if(i/st1==1){
                st2=st1;
                st1=st1*2;
            }
             if(i<st1) ret[i]=ret[i-st2]+1;

        }
        return ret;
    }
}

The picture shows the result after submission
The results show that

Published 10 original articles · Likes2 · Visits 1928

Guess you like

Origin blog.csdn.net/yuhao22/article/details/51028993