191. Number of 1 Bits [easy] (Python)

来源:互联网 发布:关于网络诈骗的作文800 编辑:程序博客网 时间:2024/04/24 21:09

题目链接

https://leetcode.com/problems/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.

题目翻译

写一个函数,输入一个无符号整数,输出这个整数二进制表示中有多少个 ’1‘ (该结果也被称为“Hamming weight”)。

比如,32位整数 ‘11’ 的二进制表示为 00000000000000000000000000001011 ,所以函数应该返回3。

思路方法

思路一

按照定义,将输入的数表示成二进制的字符串,数一下有多少个1即可。

代码

class Solution(object):    def hammingWeight(self, n):        """        :type n: int        :rtype: int        """        return bin(n).count('1')

思路二

通过移位操作,一位一位的判定是否是数字1。

代码

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

思路三

利用 n&(n-1) 的trick。简单的说,运算 n = n&(n-1) 可以将n最低位的1变成0,这里不证明。循环进行该运算,循环次数就是n的二进制表示中1的个数。

代码

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

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51323188

0 0
原创粉丝点击