My 2ms simple java solution, bit shifting


  • 0
    H
    public int hammingWeight(int n) {
        int result = 0;
        for(int i=0; i<32; i++){
            result += n&1;
            n >>= 1;
        }
        return result;
    }
    

    Can we call the "built-in" function ? Such as:

        public int hammingWeight(int n) {
            return Integer.bitCount(n);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.