#include<stdio.h>
#include<assert.h>
//1.所有数先异或
//2.找出异或结果二进制的哪一位是1
//3.以第n为1,分一组,0分一组,然后异或
void find_single_dog(int arr[], int sz, int* pd1, int* pd2)
{
int i = 0;
int ret = 0;
//1.异或
for (i = 0; i < sz; i++)
{
ret ^= arr[i];
}
//2.计算二进制中左右边的第几位是1
int pos = 0;
for (pos = 0; pos < 32; pos++)
{
if (((ret >> pos) & 1) == 1)
{
break;
}
}
for (i = 0; i < sz; i++)
{
if (((arr[i] >> pos) & 1) == 1)
{
*pd1 ^= arr[i];
}
else
{
*pd2 ^= arr[i];
}
}
}
int main()
{
int arr[] = { 1,2,3,4,5,1,2,3,4,6 };
int sz = sizeof(arr) / sizeof(arr[0]);
int dog1 = 0;
int dog2 = 0;
find_single_dog(arr, sz, &dog1, &dog2);
printf("%d %d", dog1, dog2);
return 0;
}
#include<ctype.h>
#include<limits.h>
//2. 把字符串转换成整数
enum status
{
VALID,
INVALID
}sta = INVALID;//默认非法
int my_atoi(const char* str)
{
int flag = 1;
assert(str);
if (*str == '\0')
return 0;//非法
//跳过空白字符
while (isspace(*str))
{
str++;
}
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
int ret = 0;
while (*str)
{
if (isdigit(*str))
{
//越界
ret = ret * 10 + flag*(*str - '0');
if (ret > INT_MAX || ret < INT_MIN)
{
return 0;
}
}
else
{
return (int)ret;
}
str++;
}
if (*str == '\0')
{
sta = VALID;
}
return (int)ret;
}
int main()
{
char arr[200] = "123456";
int ret = my_atoi(arr);
if (sta == INVALID)
{
printf("非法返回:%d\n", ret);
}
else if(sta == VALID)
{
printf("合法转化:%d\n", ret);
}
return 0;
}