问题链接:HDU1563 Find your present!,HDU2095 find your present(2)。
问题简述:(略)
问题分析:For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card number of 3, because 3 is the number that different from all the others.
程序说明:C语言中,异或运算符是“^”。因为a^a=0,那么要找出单独的数(唯一一个出现奇数次的数),只需要将所有的数进行异或运算即可。
- #include <stdio.h>
- int main(void)
- {
- int n, v, ans;
- while(scanf("%d", &n) != EOF) {
- // 判定结束条件
- if(n == 0)
- break;
- // 读入数据并计算
- ans = 0;
- while(n--) {
- scanf("%d", &v);
- ans ^= v;
- }
- // 输出结果
- printf("%d\n", ans);
- }
- return 0;
- }
学到的点:
异或可以用来找一个数字串中独一无二(或者奇数次)的那个数(其中,其他数都成双成对即偶数次)!
用初始值为0的ans依次异或每一个数,最终,ans值即其中那个奇数次的数值!(异或满足交换律和结合律,a^a=0!)