计算一个整数中含1的个数

#include "stdafx.h"
#include <stdio.h>

#include "t7.h"


int CountOf1(int num)
{
	int count = 0 ;

	while(num > 0){
		if(num & 1 != 0 ){
			count++;
		}
		num >>= 1;
	}
	return count;
}


int t7(void)
{
	printf("CountOf1(4) = %d\n", CountOf1(4));
	printf("CountOf1(124) = %d\n", CountOf1(124));
	printf("CountOf1(1234) = %d\n", CountOf1(1234));
	printf("CountOf1(4123) = %d\n", CountOf1(4123));

	return 0;
}
/*
CountOf1(4) = 1
CountOf1(124) = 5
CountOf1(1234) = 5
CountOf1(4123) = 5
Press any key to continue . . .
*/

 

posted @ 2015-07-08 14:49  oucaijun  阅读(320)  评论(0编辑  收藏  举报
下载TeamViewer完整版 下载TeamViewer