全部
文章
模考
课程
查分
报名
论坛
您现在的位置:考试大 >> 计算机二级 >> C++ >> C++实例编程 >> 文章内容

计算一个数的二进制表示中有多少个1

来源:考试大   【考试大:助你将考试一网打尽】   2007年10月31日
  这个阶段的我好像很喜欢把玩code。拿到Code会想它是否能够工作。先使用,再Trace,然后总结归纳。这些都是从Points C中摘录的。不知道文章该该怎么分类。所以暂且归为翻译这一栏目。 
现在看来还是觉得这些简短的Code很经典。 
  
*********************************************方法一********************************************************** 

/**//* 
** This function returns the number of 1-bits that appeared in 
** the argument value. 
*/ 
int 
count_one_bits( unsigned value ) 
...{ 
 int ones; 

 /**//* 
 ** While the value still has some 1-bits in it ... 
 */ 
 for( ones = 0; value != 0; value = value >> 1 ) 
  /**//* 
  ** If the low-order bit is a 1, count it. 
  */ 
  if( value % 2 != 0 ) 
   ones = ones + 1; 

 return ones; 


******************************************方法二******************************************* 

/**//* 
** This function returns the number of 1-bits that appeared in 
** the argument value. 
*/ 
int 
count_one_bits( unsigned value ) 
...{ 
 int ones; 

 /**//* 
 ** While the value still has some 1-bits in it ... 
 */ 
 for( ones = 0; value != 0; value >>= 1 ) 
  /**//* 
  ** If the low-order bit is a 1, count it. 
  */ 
  if( ( value & 1 ) != 0 ) 
   ones += 1; 

 return ones; 
} 来源:考试大-计算机二级考试

责编:drfcy  评论 纠错

 

考试大网校:等级考试网络课程免费试听
课程名称 讲师 优惠价 试听 报 名
 2011全国计算机等级二级公共基础 刘德强 ¥50
试听
 2011全国计算机等级考试二级VF 刘德强 ¥100
试听
 2011全国计算机等级考试二级VB 李琳玲 ¥100
试听
 2011全国计算机等级考试二级C语言 陈翠娥 ¥100
试听
 2011全国计算机等级考试三级网络技术 邱春荣 ¥100
试听
网友跟贴

暂无跟贴,欢迎您发表意见

 
 
跟贴共0
笔 名 :
网友评论仅供其表达个人看法,并不表明考试大同意其观点或证实其描述
网校免费试听