返回整数中为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");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值