标签:
#include <stdio.h> #include <stdlib.h> /* 有102个整数, 其中有50个数出现了两次, 2个数出现了一次, 找出出现了一次的那2个数。 */ /* 思路: 所有数异或得到两个单独数a,b的异或值c, 指出c为1的某位。 根据pos位为1或者为0将数组划分为两个组, 再分别对这两个组进行异或, 即可得到:a,b。 */ /* 注:结构体要放在函数声明前 */ typedef struct { int num1; int num2; }TwoNumber; int isOdd(int num); int getOne(int *arr, int length); int getPos(int number); TwoNumber getTwoNumber(int *arr, int length); int main(){ int length = 0; //整数个数 scanf("%d", &length); if (isOdd(length)) //判断是否是偶数 printf("Please input an even number.\n"); else{ int * numbers = (int*)malloc(length * sizeof(int)); //存储这length个整数 printf("Please input %d number: \n", length); int tmp; for (int i = 0; i < length; ++i){ scanf("%d", &tmp); numbers[i] = tmp; } TwoNumber tnumber = getTwoNumber(numbers, length); printf("%d\n", tnumber.num1); printf("%d\n", tnumber.num2); } system("pause"); return 0; } TwoNumber getTwoNumber(int *arr, int length){ int number = 0; //两个单独数的异或值 for (int i = 0; i < length; ++i) number ^= arr[i]; int pos = getPos(number); int num_1 = 0; //第一组数的异或值 int num_2 = 0; //第二组数的异或值 for (int i = 0; i < length; ++i){ int tmp = arr[i] >> pos; if ((tmp&‘\x01‘) == 0) num_1 ^= arr[i]; else num_2 ^= arr[i]; } TwoNumber tNumber; tNumber.num1 = num_1; tNumber.num2 = num_2; return tNumber; } int isOdd(int num){ if (num % 2 == 0) return 0; else return 1; } int getOne(int *arr, int length){ int num = 0; for (int i = 0; i < length; ++i) num ^= arr[i]; return num; } int getPos(int number){ //某个不为0的数,二进制中第一个1的位置 int pos = 0; while ((number&‘\x01‘) == 0){ pos++; number >>= 1; } return pos; }
标签:
原文地址:http://www.cnblogs.com/mutaohengheng/p/5104743.html