【算法学习】C Single Number

题目描述 - leetcode

Given an array of integers, every element appears twice except for one. Find that single one.

C 解答

int singleNumber(int* nums, int numsSize) {
    int a = 0;
    for (int i = 0; i < numsSize; i++) {
        a = a ^ nums[i];
    }
    
    return a;
}

分析

XOR
The bitwise XOR (exclusive or) performs a logical XOR function, which is equivalent to adding two bits and discarding the carry. The result is zero only when we have two zeroes or two ones.
XOR can be used to toggle the bits between 1 and 0. Thus i = i ^ 1 when used in a loop toggles its values between 1 and 0.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,793评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,906评论 0 0
  • 在巴黎的日子,大多数的时光游走在塞纳河两岸。左岸的浪漫,右岸的典雅,在时光的漫不经心中日复一日。塞纳河高贵静谧地流...
    雨巷子阅读 709评论 2 6
  • 【费斯汀格法则:人生的幸福密码】导读:生活中,看似互不相干的事情,却可能有着某种内在的联系,你的一个小小的举动不仅...
    丁尔阅读 199评论 0 0
  • 今年7月份父母收到了面谈通知书,马上安排预约广州体检中心日期。这个体检,事前要填好体检表格,发送电子邮件到体俭中心...
    Eileen_b027阅读 864评论 0 0