191. Number of 1 Bits

Source: Internet
Author: User
Tags bit set

Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as thehamming weight ).

For example, the 32-bit integer ' One ' 00000000000000000000000000001011 has a binary representation, so the function should return 3.

Solution 1:

It seems to be a very simple subject, but it is flawed when you do it.

Idea: Save a count, each time n to the right one bit, check whether the last one is 1, is 1 will count plus one.

Note that the shift number does not change the value itself, but it is not allowed to be assigned.

Pay attention to the situation of overflow, so you can not put N in the condition of while to make judgments.

Bit manipulation Ref:

Http://www.tutorialspoint.com/java/java_basic_operators.htm

 Public classSolution {//You need to treat N as an unsigned value     Public intHammingweight (intN) {intCount=31; intRes=0;  while(count>=0)        {            if((n&1)!=0) {res++; } N=n>>>1; Count--; }        returnRes; }}

Solution2:

See discussion, incredibly have a cheat Method!!!

return Integer.bitcount (n);

Solution3:

 Public classSolution {//You need to treat N as an unsigned value     Public intHammingweight (intN) {intCount = 0; intMask = 1; inti = 0;  while(I < 32) {            if((n&mask)! = 0) {Count++; } Mask<<= 1; I++; }        returncount; }}

The idea is the same as 1, but this is every time I move. Shorthand for shift: <<=,>>=. >>> three arrows is fill left by 0.

Solution 4:

 public  class    solution { //  public  int  hammingweight ( N) { int  count = 0;  for  (count = 0; n! = 0; Count++ &= n-1; //  Clear the least significant bit set     count; }}

This solution is so ingenious! The rightmost 1 is cleared, and the number of 1 is zeroed out how many times. Then accumulate the number of times

111000 & 110111=110000

110000 & 101111 =100000

100000 & 011111 =000000

191. Number of 1 Bits

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.