当前位置:网站首页>[brush through sword finger] sword finger offer II 003 Number of 1 in the first n digit binary

[brush through sword finger] sword finger offer II 003 Number of 1 in the first n digit binary

2022-06-09 01:23:00 Wind fall_

Integer article - The finger of the sword Offer II 003. front n A number in binary 1 The number of

Original link : The finger of the sword Offer II 003. front n A number in binary 1 The number of

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-t8c8NYxf-1654664972724)(https://cdn.jsdelivr.net/gh/FengLuo97/imgurl/img202206081257747.png)]

analysis

Simple solution : By binary operation , Every time you move right 1 position , And bitwise pair 1 The sum of this number can be calculated 1 The number of

Advanced solution : adopt i & (i-1) seek 1 The number of . Consider a binary number i = 1100, be i-1 = 1011, that i & (i-1) = 1000, At this point, we find a value which is 1 Bit , Add one counter , Cycle until i by 0, The number of cycles is the binary of that number 1 The number of .

For the naive solution , The time complexity is O(n*k),k Is the number of bits in binary ;

For advanced solution , The time complexity is O(n*m),m It is... In binary 1 Number of digits ;

Code

Simple solution

class Solution {
    
    public int[] countBits(int n) {
    
        int[] ans = new int[n + 1];
        
        for (int i = 0; i <= n; i++) {
    
            int cnt_One = 0;
            int temp = i;
            while (temp != 0) {
    
                if ((temp & 1) == 1) {
    
                    cnt_One++;
                }
                temp = temp >> 1;
            }
            ans[i] = cnt_One;
        }

        return ans;
    }
}

 Insert picture description here
Advanced solution

class Solution {
    
    public int[] countBits(int n) {
    
        int[] ans = new int[n + 1];

        for (int i = 0; i <= n; i++) {
    
            int cnt_One = 0;
            int temp = i;
            while (temp != 0) {
    
                temp = temp & (temp - 1);
                cnt_One++;
            }
            ans[i] = cnt_One;
        }
        
        return ans;
    }
}

 Insert picture description here
Writing is not easy , Ask for attention , No attention to , Just like it !
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lyMxWZoP-1654664972726)(https://cdn.jsdelivr.net/gh/FengLuo97/imgurl/img202206081257357.gif)]

原网站

版权声明
本文为[Wind fall_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090122098899.html