欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

leetcode 136 Single Number bit Option

程序员文章站 2022-06-09 14:15:01
Linked Url:https://leetcode.com/problems/single-number/ Given a non-empty array of integers, every element appears twice except for one. Find that sin ......

linked url:

given a non-empty array of integers, every element appears twice except for one. find that single one.

note:

your algorithm should have a linear runtime complexity. could you implement it without using extra memory?

example 1:
input: [2,2,1] output: 1
example 2:
input: [4,1,2,1,2] output: 4

solution:

the method is xor option, principles is  : 0 xor 0 = 0; 0 xor 1 = 1;any  num xor itself  =  0,so we pass the array and xor its elements all,so the result  which is we want.

ac code follow: 

1 class solution {
2 public:
3     int singlenumber(vector<int>& nums) {
4         int res = nums[0];
5         for(int i = 1;i < nums.size();++i)
6             res = nums[i]^res;
7         return res;
8     }
9 };