1.编写函数:unsigned int reverse_bit(unsigned int value); 这个函数的返回值value的二进制位模式从左到右翻转后的值。
如: 在32位机器上25这个值包含下列各位: 00000000000000000000000000011001
翻转后:(2550136832) 10011000000000000000000000000000 程序结果返回: 2550136832
2.不使用(a+b)/2这种方式,求两个数的平均值
如: 在32位机器上25这个值包含下列各位: 00000000000000000000000000011001
翻转后:(2550136832) 10011000000000000000000000000000 程序结果返回: 2550136832
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
unsigned int reverse_bit(unsigned int value)
{
unsigned int target=0;
unsigned int bit=1;
int i=0;
for(i=0;i<32;i++)
{
if(value & (bit<<i))
target |= bit<<(31-i);
}
return target;
}
int main()
{
unsigned int value;
scanf("%u",&value);
printf("%u\n",reverse_bit(value));
return 0;
}
2.不使用(a+b)/2这种方式,求两个数的平均值
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//法一:
int main()
{
int a=10;
int b=20;
printf("%d\n",(a & b)+((a^b)>>1));
}
//法二:
//int main()
//{
// int a=20;
// int b=10;
// printf("%d\n",a+((b-a)>>1));
//}
3.编程实现: 一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。 请找出这个数字。(使用位运算)
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int find_single(int *arr,int len)
{
int single=arr[0];
int i=0;
for(i=1;i<len;i++)
{
single ^= arr[i];
}
return single;
}
int main()
{
int arr[]={1,2,3,4,5,1,2,3,4,5,7};
int len=sizeof(arr)/sizeof(arr[0]);
printf("%d\n",find_single(arr,len));
return 0;
}
4. 有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student". 要求: 不能使用库函数。只能开辟有限个空间(空间个数和字符串的长度无关)
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
void reverse(char *start,char *end)
{
while(start < end)
{
*start ^= *end;
*end ^= *start;
*start ^= *end;
start++;
end--;
}
}
void switch_string(char *str)
{
char *fast=str;
char *slow=fast;
while(*fast != '\0')
{
if(isspace(*fast))
{
reverse(slow,fast-1);
fast++;
slow=fast;
}
else
{
fast++;
}
}
reverse(slow,fast-1);
reverse(str,fast-1);
}
int main()
{
char str[]="student a am i";
assert(str);
switch_string(str);
printf("%s\n",str);
return 0;
}