用异或实现两个数的交换&x&(x-1)表达式作用&计算前1500个丑数

**************用异或实现两个数的交换问题**************
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值