Leetcode record 191. Number of 1 Bits

Source: Internet
Author: User
public class Solution {
    //your need to treat n as a unsigned value public
    int hammingweight (int n) {
        int coun t=0;
        while (n!=0) {
            if ((n&1) ==1)
                count++;
            n>>>=1;
        }
        return count;
    }
}

The use of >>> instead of >>,>>> is an unsigned right shift, ignoring the sign bit.

Possible error: did not give n&1 braces, reported bad operand types for binary operator ' & ' ERROR

mainly because = = = = Priority is greater than & cause

Or:

return Integer.bitcount (n);


Or:

Need to treat n as a unsigned value public
    int hammingweight (int n) {
        int count = 0;
        while (n!=0) {
            n&= n-1;
            count++;
        }
        return count;
    
To subtract 1 from an integer, and then to do the same with the original integer, will turn the integer rightmost 1 into 0, then how many times the binary representation of an integer number 1, you can do this operation.

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.