The number of 1 in binary _java

Source: Internet
Author: User
Preface


will be writing some regular interview questions recently, the test will share with you after the





Displacement Method


is only suitable for positive numbers:




The
shift method is to determine whether the minimum bit of n is 1, and the time complexity is O (logn)


Copy Code code as follows:

int nativeonenum (int n)
{
int count = 0;

while (n) {
if (n & 1) count + +;
n >>= 1;
}

return count;
}



is no problem for positive numbers, but if n is negative, here's the problem, with negative 8 as an example, the binary complement form is 11111111|11111111|11111111|11111000|, and the right one becomes the 11111111|11111111 |11111111|11111100|, because it is a negative number, so the sign bit will continue to fill 1, resulting in the last 1, the death cycle





in this case, we can use the variable flag = 1, from right to left and n comparison, 32-bit int up to 32 times to know the number of n 1


Copy Code code as follows:

int onenum (int n)
{
int count, flag;

for (count = 0, flag = 1; flag; flag <<= 1) {
if (flag & N) count + +;
}

return count;
}



Rapid Method


This solution is that the number of binary 1 is only related to 1 of the number of digits, N &amp; (n-1) quickly remove the leftmost 1, such as 7 (0111) &amp; 6 (0110) = 6 (0110), quickly remove the leftmost 1


Copy Code code as follows:

int quickone (int n)   
{  
    I NT count = 0;  

    while (n) {  
       ;  Count ++;  
        n = n & (n-1);  
&nbs p;  }  

    return count;  
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.