LeetCode 题解(201) : Number of 1 Bits

来源:互联网 发布:免费网吧代理软件 编辑:程序博客网 时间:2024/06/07 00:43

题目:

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

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

题解:

C++版:

class Solution {public:    int hammingWeight(uint32_t n) {        int r = 0;        while(n) {            r += (n & 1);            n >>= 1;        }        return r;    }};

Java版:

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

Python版:

class Solution(object):    def hammingWeight(self, n):        """        :type n: int        :rtype: int        """        r = 0        while n != 0:            r += n & 1            n >>= 1        return r


0 0