程序员面试——计算二进制数中1的个数

本文介绍了三种方法用于计算整数的二进制表示中1的个数,包括Count1、Count2和Count3函数。Count1方法在处理负数时存在死循环问题,Count2和Count3方法则可以处理32位内的正负整数。此外,还提供了一个使用Count3方法判断整数是否为2的整数次幂的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文提供了三种方法,分别计算一个数的二进制表示中1的个数。方法和解释分别见Count1, Count2, Count3函数。

只有Count1不能满足负数要求(会死循环进去),其他两个都可以操作32b以内正负数。

Count1:每次将x末位与1相与,看最后以为是否为1, 然后将x右移

Count2:将变量y从1开始与x相与,然后每次将y左移,和上个方法类似

Count3:每次将x&=(x-1)可以将最右边一个1变为0;

该方法应用:e.g. 如何用一个语句判断一个整数是不是2的整数次幂?

#define Is2P(x) x&(x-1)?0:1

  1. /********************/
  2. //@Discription: Count the number of '1' in binary number
  3. //@Author: ZRQ Sophia
  4. //@Create Date:2012-5-22
  5. /********************/
  6. #include"stdio.h"
  7. int Count1(int x)
  8. {
  9. int c=0;
  10. while(x)
  11. {
  12. c+=x&1;
  13. x>>=1;
  14. }
  15. return c;
  16. }
  17. //Bug:当x=0x80000000(negative)时,x>>1要保证还是负数,因此不是0x40000000,而是=0xc0000000
  18. //i.e. input -2147483648(0x80000000),x>>1=-107374124(0xc0000000),而非2^30(0x40000000)
  19. //这样最后会出现0xff导致死循环
  20. int Count2(int x)
  21. {
  22. int c=0;
  23. unsigned int y=1;
  24. while(y)
  25. {
  26. c+=x&y?1:0;
  27. y<<=1;
  28. }
  29. return c;
  30. }
  31. //Problem:不知道x的位数,会造成一些冗余运算,不过没关系,32位pc最多运算32次嘛
  32. //不是问题的问题
  33. int Count3(int x)
  34. {
  35. int c=0;
  36. while(x)
  37. {
  38. x&=x-1;
  39. c++;
  40. }
  41. return c;
  42. }
  43. int main()
  44. {
  45. int x;
  46. while(scanf("%d",&x)!=EOF)
  47. {
  48. printf("%d\n%d\n%d\n",Count1(x),Count2(x),Count3(x));
  49. }
  50. return 0;
  51. }
/********************/
//@Discription: Count the number of '1' in binary number
//@Author: ZRQ Sophia
//@Create Date:2012-5-22
/********************/

#include"stdio.h"

int Count1(int x)
{
	int c=0;
	while(x)
	{
		c+=x&1;
		x>>=1;
	}
	return c;
}
//Bug:当x=0x80000000(negative)时,x>>1要保证还是负数,因此不是0x40000000,而是=0xc0000000
//i.e. input -2147483648(0x80000000),x>>1=-107374124(0xc0000000),而非2^30(0x40000000)
//这样最后会出现0xff导致死循环

int Count2(int x)
{
	int c=0;
	unsigned int y=1;
	while(y)
	{
		c+=x&y?1:0;
		y<<=1;
	}
	return c;
}
//Problem:不知道x的位数,会造成一些冗余运算,不过没关系,32位pc最多运算32次嘛
//不是问题的问题

int Count3(int x)
{
	int c=0;
	while(x)
	{
		x&=x-1;
		c++;
	}
	return c;
}

int main()
{
	int x;
	while(scanf("%d",&x)!=EOF)
	{
		printf("%d\n%d\n%d\n",Count1(x),Count2(x),Count3(x));
	}
	return 0;
}

源题目出处:http://zhedahht.blog.163.com/blog/static/25411174200731844235261/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值