Skip to content

ยท 1 min read

Blind 75 - Number of 1 Bits

Check if the last bit is 1 by (n&1). Do the right unsigned shift (logical shift >>>). Loop.

[Video]

[Problem explanation in English]

Return the number of binary ones. also known as hamming weight.

Link

Approaches

O(time) time; O(space) space; n lines

Check if the last bit is 1 by (n&1). Do the right unsigned shift (logical shift). Loop.

    public int hammingWeight(int n) {
        int count = 0;

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

        return count;
    }

Get new posts by email

No spam. Unsubscribe anytime. Or grab the RSS feed.

Mailto-based for now. ButtonDown / ConvertKit can replace this form later.


Comments lazy-load on scroll. Prefer GitHub? Giscus activates once PUBLIC_GISCUS_* env vars are set (see Giscus.astro).

Index

Index

Back to Blog