Number of 1 Bits - LeetCode

来源:互联网 发布:99re最新网站地址域名 编辑:程序博客网 时间:2024/04/29 19:47

Number of 1 Bits - LeetCode

题目:

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.

分析:

这样的题目一看和1有关系的就应该是位计算的题目,这里我们通过判断 n^1(异或)与n的关系,因为如果n的末位是1的话,n^1后末位将是0,即n-n^1 = 1。例如11的二进制为1011,11^1为1010,相差1,然后我们左移n,换下一位来重复此过程,直到n=0。

虽然位计算感觉比较抽象,但是我们用多了后还是很容易想到的,毕竟也就几种变化,程序员嘛,010101。。。


代码:

class Solution:    # @param n, an integer    # @return an integer    def hammingWeight(self, n):        res =  0        while n != 0:            if n - (1^n) == 1:                res +=1            n = n>>1        return res



0 0
原创粉丝点击