//第一种:短除法 int count_one(unsigned num) { int count = 0; while (num != 0) { if (num % 2 == 1) { count++; } num /= 2; } return count; } //第二种:移位按位与1法 int count_one(int num) { int count = 0; int i = 0; for (i = 0; i < 32; i++) { count += (num >> i) & 1; } return count; } //第三种:num与num-1进行按位与 int count_one(int num) { int count = 0; while (num != 0) { num = num & (num - 1); count++; } return count; } int main() { int num = 0; int count = 0; printf("请输入一个数字>:"); scanf("%d", &num); count = count_one(num); printf("1的个数为:%d\n", count); return 0; }
c语言| |二进制中1的个数
最新推荐文章于 2023-06-17 22:06:24 发布