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
- 191. Number of 1 Bits [easy] (Python)
- 191. Number of 1 Bits (Easy)
- 191. Number of 1 Bits 难度:easy
- LeetCode 191. Number of 1 Bits (Easy)
- Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]
- Easy-题目15:191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits (Easy) (cpp)
- 【leetcode】191. Number of 1 Bits(easy)
- [Leetcode 191, Easy] Number of 1 Bits
- Number of 1 Bits (easy)
- 【Leetcode】Number of 1 Bits(easy)
- Easy 191题 Number of 1 Bits
- leetcode191[easy]---Number of 1 Bits
- 191. Number of 1 Bits Leetcode Python
- [leetcode: Python]191.Number of 1 Bits
- 191.Number of 1 Bits
- 191.Number of 1 Bits
- 191. Number of 1 Bits
- 简易内核调度设计 --基于TQ2440(ARM9)的实现(1)
- 3D图片轮播
- 关于MCNS/DOCSIS兼容RF接口的RF接口MIB
- Java 8 中新的 Date 和 Time 类入门详解, DateUtil ,以后可以少写几个了,关键是线程安全了
- 第一次使用Android Studio时你应该知道的一切配置
- 191. Number of 1 Bits [easy] (Python)
- unsolved 2 db2 issues
- 如何手动安装VMware Tools? VMvare三种网络模式?
- Spring 3.1中对JSR-330的支持
- 非阻塞socket设置方法
- Makefile 使用总结
- PowerDesigner V16.5 安装文件 及 破解文件
- SQL计划备份任务及共享文件同步异地备份
- 32位与64位的区别