编程实现:
一组数据中只有一个数字出现了一次,其他所有数字都是成对出现的,请找出这个数字。
#include <stdio.h>
#include <stdlib.h>
int find_num(int* num,int zs) //自定义函数
{
//int i=0;
int t=0;
// for (i=0;i<zs;i++)
while (zs)
{
t=* num++ ^t; //使所有数字之间异或,相同为0,0与任意数异或为本身
zs--;
}
return t;
}
int main ()
{
int s=0;
int arr[20]={3,5,3,9,5,2,2,7,9,15,7}; //按要求定义一组数字
s=sizeof arr/sizeof arr[0]; //计算数组元素个数
find_num(arr,s);
printf ("%d\n",find_num(arr,s); ); //链式访问输出返回值
system ("pause");
}
编程实现:
输入任意数,把它二进制的任意位改成1或0,然后输出改变后的十进制例如:
a=13;
……00000000000001101
把第4位改为0,得……0000000000000101,其输出十进制为5
#include <stdio.h>
int set_bit(int a, int pos, int flag)
{
int b = 1 << (pos - 1); //改变任意位
if (flag == 0)
{
a &= ~b; //0与任意数按位与都为0,把任意位改0
}
else
{
a |= b;
} //1与任意数按位或都为1,把任意位改1
return a;
}
int main()
{ int e=0;
int g=0;
int c=0;
int ret=0;
printf ("输入一个数,操作数,置1或0\n");
scanf ("%d%d%d",&e,&g,&c);
ret=set_bit(e,g,c);
printf("%d\n", ret);
return 0;
}