写一个函数,求一个数的二进制(补码)表示中有几个1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int count_one(int n) {
int count = 0;
while (n) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
return count;
}
int main() {
int a = 0;
scanf("%d", &a);
//写一个函数,求a的二进制(补码)表示中有几个1
int count = count_one(a);
printf("count=%d\n", count);
return 0;
}
15
count=4
两个整数的二进制表达中,有多少个位不同?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//两个整数的二进制表达中,有多少个位不同?
int get_diff(int m, int n) {
int tmp = m ^ n;
int count = 0;
while (tmp) {
tmp = tmp & (tmp - 1);
count++;
}
return count;
}
int main() {
int m = 0;
int n = 0;
scanf("%d%d", &m, &n);
int count = get_diff(m, n);
printf("count = %d\n", count);
return 0;
}
1999 2021
count = 3
分别打印一个整数二进制序列中所有偶数位和奇数位
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//分别打印一个整数二进制序列中所有偶数位和奇数位
void Print(int m) {
int i = 0;
printf("奇数位:\n");
for (i = 30; i >= 0; i -= 2) {
printf("%d ", (m >> i) & 1);
}
printf("\n");
printf("偶数位:\n");
for (i = 31; i >= 1; i -= 2) {
printf("%d ", (m >> i) & 1);
}
}
int main() {
int m = 0;
scanf("%d", &m);
Print(m);
return 0;
}
10
奇数位:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
偶数位:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1