一、2的次幂
题目描述:给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
解法: n&(-n)将除最后一位的1之外的所有的数字置为0(因为-n=~n+1,所以n&(-n)==n&(~n+1)),例如
7对应的二进制为0111
-7对应的二进制为1001
7&(-7)=0001
代码实现:
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (-x)) == x;
}
二、位1的个数
题目描述:编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
思想:使用n&(n-1)逐个消去最后一个1
代码实现:
public int hc(int n)
{ int count=0;
while(n>0)
{
n=n&(n-1);//消除最后一个1
++count;
}
return count;
}
三、[0,num]范围内的整数的二进制形式中1的总数
题目描述:给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
思想:使用动态规划来下实现数字的推导.例如 1(0001)2(0010) 3(0011) 4(0100) 5(0101) 6(0110 ) 7(0111) 8(1000)等
1=0+2^0(pop_count(1)=pop_count(0)+1)
2=0+2^1( pop_count(2)=pop_count(0)+1)
3=1+2^1 (pop_count(3)=pop_count(1)+1)
4=0+2^2(pop_count(4)=pop_count(0)+1);
5=1+2^2(pop_count(5)=pop_count(1)+1);
6=2+2^2(pop_count(6)=pop_count(2)+1);
7=3+2^2(pop_count(7)=pop_count(3)+1)
8=0+2^3(pop_count(8)=pop_count(0)+1)
i+b=i+2^b(ans[i+b]=ans[i]+1);
[0,0) 推导出 [0,1) 推导出 [0,3) 推导出[0,7) 推导出...
代码实现:
public int[] countBit(int num)
{
int [] ans=new int [num+1];
int i=0,b=1;
while(b<=num)
{
while(i<b&&i+b<=num)
{
ans[i+b]=ans[i]+1;
++i;
}
i=0;
b=b<<1;
}
return ans;
}
实现结果:
public static void main(String args[])
{
int ac[]=count_bit(3);
for(int i=0;i<ac.length;i++)
System.out.println(ac[i]);
}
四、汉明距离
题目描述:两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
思想:
就是计算x^y中的1中的个数
代码实现:
public int hammingDistance(int x, int y)
{
int i = x ^ y;
int count = 0;
while (i != 0) {
if ((i & 1) == 1) //消除最后一位1
{
count++;
}
i = i >> 1;//右移
}
return count;
}
五、交替二进制数
题目描述:给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。
思想:保留最后一位,然后右移,再判断是否相同
代码实现:
public boolean has_Al(int n)
{ int pre=-100;
boolean is_has=false;
while(n!=0)
{ if(pre!=-100&&pre==(n&1))
{
is_has=false;
break;
}
else
{
pre=n&1;
//判断最后一位是否为1
n=n>>1;//清除最后一位
}
}
return is_has;
}
下次再写