原题: write the function int bitcount(short input) that takes a short as input and
returns an int. the function returns the number of bits set in the input
variable. for instance:
bitcount(7) --> 3
bitcount(2543) --> 9
bitcount(11111) --> 9
代码:
/********************************************************************
created: 2006/06/14
created: 14:6:2006 16:53
filename: c:/documents and settings/administrator/my documents/近期阅读/mytinything/bitcount.c
file path: c:/documents and settings/administrator/my documents/近期阅读/mytinything
file base: bitcount
file ext: c
author: a.tng
version: 0.0.1
purpose: 面试题
write the function int bitcount(short input) that takes a short as input and
returns an int. the function returns the number of bits set in the input
variable. for instance:
bitcount(7) --> 3
bitcount(2543) --> 9
bitcount(11111) --> 9
*********************************************************************/
#include <stdio.h>
/*
* name: bitcount
* params:
* input [in] 需要分析的 short 型数
* return:
* 输入参数 input 的为1的位数
* notes:
* 计算 input 中为1的位数
* author: a.tng 2006/06/14 17:00
*/
int bitcount(short input)
{
int n_ret = 0;
/* 只要 input 不为0,则循环判断 */
while (0 != input)
{
/* 如果 input & 1 == 1 则表示最低位为1,反之则等于0 */
if (input & 1)
{
n_ret++;
}
input = input >> 1;
}
return n_ret;
}
/*
* name: main
* params:
* none
* return:
* 函数返回状态给系统
* notes:
* 系统 main 函数
* author: a.tng 2006/06/14 17:04
*/
int main()
{
/* 输入需要计算的整数 */
int n = 2543;
/* 输出 bitcount 的结果 */
printf('%d/n', bitcount((short) n));
/* 发送 pause 命令给系统 */
system('pause');
}
① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;
② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。