美文网首页
【算法学习】C Single Number

【算法学习】C Single Number

作者: Jiubao | 来源:发表于2017-02-04 16:45 被阅读14次

题目描述 - 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.

相关文章

网友评论

      本文标题:【算法学习】C Single Number

      本文链接:https://www.haomeiwen.com/subject/axxsittx.html