推荐给好友 上一篇:如何快速有效学好C语言   下一篇:高效程序员应该养成的七个习惯

面试系列1返回整数中为1的位数

原题: 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');
}

转贴于:软件水平考试_大学生考试信息门户


TAG:

我来说两句