利用shift 方式
可以搭配這個網站,線上執行
https://ideone.com/i1sUId#cmperr
#include <stdio.h>
#include <stdlib.h>
int ret_one_bit_num(unsigned int);
void main(){
int rlt = 0, input = 9;
rlt = ret_one_bit_num(input);
printf("%d have [%d] bit is 1\r\n", input, rlt);
system("pause");
}
int ret_one_bit_num(unsigned int n)
{
int count = 0;
while(n!=0)
{
if(n & 1 == 1)
count++;
n>>=1;
}
return count;
}
沒有留言:
張貼留言