我想在文件bitcount.c
中編寫一個名爲bitCount()
的函數,該函數返回無符號整數參數二進制表示中的位數。計算無符號整數中的位數
這是我到目前爲止有:
#include <stdio.h>
int bitCount (unsigned int n);
int main() {
printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n",
0, bitCount (0));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
1, bitCount (1));
printf ("# 1-bits in base 2 representation of %u = %d, should be 16\n",
2863311530u, bitCount (2863311530u));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
536870912, bitCount (536870912));
printf ("# 1-bits in base 2 representation of %u = %d, should be 32\n",
4294967295u, bitCount (4294967295u));
return 0;
}
int bitCount (unsigned int n) {
/* your code here */
}
好吧,當我運行此我得到:
# 1-bits in base 2 representation of 0 = 1, should be 0
# 1-bits in base 2 representation of 1 = 56, should be 1
# 1-bits in base 2 representation of 2863311530 = 57, should be 16
# 1-bits in base 2 representation of 536870912 = 67, should be 1
# 1-bits in base 2 representation of 4294967295 = 65, should be 32
RUN SUCCESSFUL (total time: 14ms)
不退還位的正確數目。
返回C中無符號整數參數二進制表示形式的位數的最佳方法是什麼?
你在'bitCount()'中嘗試了什麼? – ogzd 2013-02-08 20:42:10
我想你錯過了「你的代碼在這裏」。 – 2013-02-08 20:49:17
你會被允許使用'__builtin_popcount'嗎? – harold 2013-02-12 17:32:53