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

發佈了14 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章