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

//1. Programming implementation:
//How many bits are different in the binary expression of two int (32-bit) integers m and n?
//Input example:
//1999 2299
//Output example: 7
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int compare(int a, int b)
{
int i = 0;
int count = 0;
for (i = 0; i < 32; i++)
{
if (((a & 1) ^ (b & 1)) == 1)
{
count++;
}
a >>= 1;
b >>= 1;
}
printf("count=%d\n", count);
return 1;
}


int main()
{
int m = 0;
int n = 0;
scanf("%d%d", &m, &n);
compare(m, n);
system("pause");
return 0;
}


//2. Write the function:
//unsigned int reverse_bit(unsigned int value);
//The binary bit pattern of the return value of this function is reversed from left to right.
//Such as:
//The value of 25 on a 32-bit machine contains the following bits:
//00000000000000000000000000011001
//After flipping: (2550136832)
//10011000000000000000000000000000
//The program result is returned:
//2550136832
#include<stdio.h>
#include <stdlib.h>
unsigned int reverse_bit(unsigned int value)
{
int i = 0;
unsigned ret = 0; //Unsigned type, otherwise the highest bit is treated as a sign bit, and overflow
for (i = 0 ; i <= 31; i++)
  {
ret <<= 1;
ret |= (value & 1);
value >>= 1;


}
printf("ret=%u\n",ret); //%u prints an unsigned integer
}


int main()
{
int num = 0;
scanf("%d", &num);
reverse_bit(num);
system("pause");
return 0;
}


//3. Do not use (a + b) / 2 this way, find the average of the two numbers.
#include<stdio.h>
#include<stdlib.h>
int average(int x, int y)
{
int apr = 0;
avr = x - (x - y) / 2;
printf("avr=%d\n", avr);
return 1;
}


int main()
{
int a = 2;
int b = 3;
average(a, b);
system("pause");
return 0;
}


//4. Only one number appears once in a set of data.
//All other numbers appear in pairs. Please find out this number. (Using bit operation)
#include<stdio.h>
#include<stdlib.h>
int find(int arr[5],int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
int j = 0;
int count = 0;
for (j = 0; j < sz; j++)
{
if (arr[i] == arr[j])
{
count++;
}
}
if (count == 1)
{
printf("A number: %d ", arr[i]);
}
}
printf("\n");
}


int main()
{
int arr[5] = { 1, 2, 3, 1, 2 };
int sz = 0;
sz = sizeof(arr) / sizeof(arr[0]);
find(arr,sz);
system("pause");
return 0;

}








Movie: Seeds of Star Wars Gaiden.


Guess you like

Origin blog.csdn.net/lxp_mujinhuakai/article/details/53729240