【基础训练-异或的运用】find your present

问题链接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,那么要找出单独的数(唯一一个出现奇数次的数),只需要将所有的数进行异或运算即可。

  1. #include <stdio.h>  
  2.   
  3. int main(void)  
  4. {  
  5.     int n, v, ans;  
  6.   
  7.     while(scanf("%d", &n) != EOF) {  
  8.         // 判定结束条件  
  9.         if(n == 0)  
  10.             break;  
  11.   
  12.         // 读入数据并计算  
  13.         ans = 0;  
  14.         while(n--) {  
  15.             scanf("%d", &v);  
  16.             ans ^= v;  
  17.         }  
  18.   
  19.         // 输出结果  
  20.         printf("%d\n", ans);  
  21.     }  
  22.   
  23.     return 0;  
  24. }  

学到的点:

异或可以用来找一个数字串中独一无二(或者奇数次)的那个数(其中,其他数都成双成对即偶数次)!

用初始值为0的ans依次异或每一个数,最终,ans值即其中那个奇数次的数值!(异或满足交换律和结合律,a^a=0!)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值