Monday, April 23, 2018

[2018-Interview] Number of 1 Bits

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

My answer:



public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        if (n == 0) {
            return 0;
        }
        int num1Bit = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                num1Bit ++;
            }
            n = n >>> 1;
        }
        return num1Bit;
    }
}

No comments:

Post a Comment