旅途

如果想飞得高,就该把地平线忘掉

面试系列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");
}

posted on 2007-09-05 01:14 旅途 阅读(104) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理