congr / world

2 stars 1 forks source link

LeetCode : 191. Number of 1 Bits #445

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/number-of-1-bits/

image image

congr commented 5 years ago
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // return Integer.bitCount(n);

        int cnt = 0;
        int mask = 1;

        // System.out.println(Integer.toBinaryString(n));
        // System.out.println(Integer.toBinaryString(mask));
        for (int i = 0; i<32; i++) {
            // System.out.println("n & mask = "+ Integer.toBinaryString((n & mask)));
            if ((n & mask) != 0) cnt++;
            mask <<= 1;
        }

        return cnt;
    }
}
congr commented 5 years ago

image

congr commented 5 years ago

image