C language basic programming questions-3 (binary)

C language basic programming questions-3

1. Programming realization: How many bits are different in the binary representation of two int (32-bit) integers m and n?
Input example:
1999 2299
Output example: 7

#include <stdio.h>
int Once(int x,int y){
    
    
	int n = x^y;//异或之后不同位变为一,相同位为零
	int count = 0;
	while (n!=0){
    
    
		count++;
		n = n&(n - 1);
	}
	return count;
}
int main(){
    
    
	int x = 1999, y = 2299;
	printf("有%d个bit位不同\n",Once(x,y));
	return 0;
}

2. Get all the even and odd bits in an integer binary sequence, and print out the binary sequence respectively

#include <stdio.h>
void PrintTwo(int n){
    
    
	int num1[16] = {
    
     0 };
	int num2[16] = {
    
     0 };
	int i,j,k;
	for (i = 0,j=0,k=0; i < 32;++i){
    
    
		if (i%2!=0){
    
    
			num1[j] = n & 1;
			++j;
		}
		else{
    
    
			num2[k] = n & 1;
			++k;
		}
		n = n >> 1;//右移
	}
	printf("奇数位为:"); 
	for (i = j-1; i >=0;--i){
    
    
		printf("%d ",num1[i]);
	}
	printf("\n");
	printf("偶数位为:");
	for (i =k-1; i >=0; --i){
    
    
		printf("%d ", num2[i]);
	}
	printf("\n");
}
int main(){
    
    
	int n;
	scanf("%d",&n);
	PrintTwo(n);
	return 0;
}

3. Write a function to return the number of 1s in the parameter binary.
For example: 15 0000 1111 4 1

#include <stdio.h>
int One(int n){
    
    
	int count = 0;
	while (n != 0){
    
    
		count++;
		n = n&(n - 1);//每次与一次少一个1,与几次就少几个1
	}
	return count;
}
int main(){
    
    
	int n;
	scanf("%d", &n);
	printf("%d\n",One(n));
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45841205/article/details/109641601