Leetcode:Number of 1 Bits

Number of 1 Bits

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

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Answer 

沒有難度,但是有個小技巧處理二進位制,除 2 是否有餘 1 ,以及利用運算子將位元右移,我想本題的著重在於是否有想到利用位元右移吧?

Javascript

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n){
    var x = 0;
    while(n !== 0){
        x += n % 2;
        n = n>>>1;
    }
    return x;
};
//Min:144ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

C

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
int hammingWeight(uint32_t n){
    int x = 0;
    while(n != 0){
        x += n % 2;
        n = n>>1;
    }
    return x;
}
//Min:4ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

Python

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        x = 0
        while n!=0 :
            x += n%2
            n = n>>2
        return x
#Min:44ms

留言

這個網誌中的熱門文章