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

王朝other·作者佚名  2006-06-15
窄屏简体版  字體: |||超大  

原题:

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");

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航