写一个函数返回二进制中1的个数(两种方法)

#include <stdio.h>
#include <stdlib.h>

//写一个函数返回二进制中1的个数(法1:数位遍历)
int countOneNum(int n){
 int i;
 int count = 0;
 for (i = n; i; i /= 2){
  count += i % 2;
 }
 return count;
}
int main(){

 printf("%d\n", countOneNum(1000));
 system("pause");
 return 0;
}

 

 

 

 

#include <stdio.h>
#include <stdlib.h>

//写一个函数返回二进制中1的个数(法2:while)
int countOneNum(int n){
 int count = 0;
 while (n){
  n &= n - 1;
  count++;
 }
 return count;
}
int main(){

 printf("%d\n", countOneNum(1000));
 system("pause");
 return 0;
}

posted @ 2020-04-02 13:13  听说在北郭  阅读(375)  评论(0)    收藏  举报