Gidhub BE Developer

LeetCode : 191. Number of 1 Bits

2020-11-28
goodGid

191. Number of 1 Bits

Problem

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

Example

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Code (20. 11. 28)

class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {

        int ans = 0;
        int mask = 1;

        for (int i = 0; i < 32; i++) { // [1]
            if ((n & mask) != 0) {
                ans++;
            }
            mask <<= 1;
        }
        return ans;
    }
}

Reference


Recommend

Index