题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
思路:1.逐位进行&判断;
2.n&(n-1)相当于把最右边的1变为0。
10011 & 10010 = 10010
10010 & 10001 = 10000
10000 & 01111 = 00000
时间复杂度:O(n)
class Solution {
public:
int NumberOf1(int n) {
int flag=1;
int count=0;
while(flag)
{
if(flag & n)
++count;
flag=flag<<1;
}
return count;
}
};
时间复杂度:O(n),优于上例
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while(n)
{
++count;
n=n&(n-1);
}
return count;
}
};
python
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
flag=1
count=0
for i in range(32):
if flag & n:
count+=1
flag=flag<<1
return count
# write code here
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
count=0
n=n&0xffffffff #限制n的大小,为4字节
while n:
count+=1
n=n&(n-1)
return count
# write code here
扩展:
判断一个数是不是2的整数次方。
2的整数次方的特点为:仅含有一个1. 100000
n&(n-1)==0则表示仅有一个1.
输入两个整数m,n,计算需要改变m的二进制中的多少位才能得到n;
其实就是统计m,n中不同位数的个数。m^n得到对应位置不同的数。然后统计1的个数即可。