Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5699955
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类:

2006-09-07 10:37:04

原题:

  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

/*
 *  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");
}

阅读(1632) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~