void swap(int &a,int &b)
{
a^=b;
b^=a;
a^=b;
}
转换过程:a------------------------->b
a^=b a=a^b
a^b---------------------->b
b^=a b=b^a=b^(a^b)=a
a^b------------------>a
a^=b a=a^b=(a^b)^(a)=b
b------------------------->a
OK b------------------------->a
任何一位二进制数同 1 异或都会变成另外一个(0 同 1 异或的结果是 1,1 同 1 异或的结果是 0)
任何一位二进制数同 0 异或都保持不变(0 同 0 异或的结果是 0,1 同 0 异或的结果是 1)
**************x&(x-1)表达式的作用**************
1、统计1的个数
----------方法1----------
int func(int x)
{
int countx = 0;
while(x)
{
countx++;
x = x&(x-1);
}
return countx;
}
假定x = 9999
10011100001111
答案: 8
思路: 将x转化为2进制,看含有的1的个数。
注: 每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。
----------方法2----------
unsigned char count_ones(unsigned int data)
{
unsigned char c = 0;
unsigned int mask = 0x80000000;
for(;mask>0;mask=mask>>1)
{
if((data&mask)==mask)
{
c++;
}
}
return c;
}
2、判断一个数(x)是否是2的n次方
#include <stdio.h>
int func(int x)
{
if( (x&(x-1)) == 0 )
return 1;
else
return 0;
}
int main()
{
int x = 8;
printf("%d\n", func(x));
}
注: (1) 如果一个数是2的n次方,那么这个数用二进制表示时其最高位为1,其余位为0。
(2) == 优先级高于 &
转载自:http://hi.baidu.com/zengzhaonong/item/b8e4e78ea7e8a3d45f0ec17b
**************计算前1500个丑数(诺西笔试题)**************
Ugly numbers are numbers whose only prime factors are 2,3or 5.The sequence 1,2,3,4,5,6,8,9,10,12,15,…shows the first 11 ugly numbers. By convention,1 is included.
Write a time efficient program to find and print the 1500’th ugly number
bool judge(long long x)
{
while(x % 2 == 0) x/=2;
while(x % 3 == 0) x/=3;
while(x % 5 == 0) x/=5;
return (x==1);
}
int ugly_number()
{
int m = 0;
long long a;
for( a = 1 ;m < 1500; a++){
if(judge(a)){
m++;
printf("%d:%d\n",m,a);
}
}
return a;
}