首页 技术 正文
技术 2022年11月21日
0 收藏 675 点赞 3,295 浏览 1186 个字

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的个数。

解法:位操作Bit Manipulation

使用n&(n-1)的方法

假使 n =0x110101

n       n-1     n&(n-1)

step1: 110101 110100 110100

step2: 110100 110011 110000

step3: 110000 101111 100000

step4: 100000 011111 000000

发现有几个1,就循环几次n&(n-1)得到0。

时间复杂度:O(M),M是n中1的个数

Java:

public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count ++;
}
return count;
}
}  

Python:

class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result

Python:

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

Python:

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

C++:

class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
for (int i = 0; i < 32; ++i) {
res += (n & 1);
n = n >> 1;
}
return res;
}
}; 

C++:

class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
for (; n; n &= n - 1) {
++count;
}
return count;
}
};

 

类似题目:

[LeetCode] 190. Reverse Bits 翻转二进制位

 

All LeetCode Questions List 题目汇总

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898